Suppose we are iterating over the elements of an array and adding them to another array.
If we are adding the elements via the push
method, then in each iteration of the loop, the element we are iterating over will be added to the end of the array. So, the original order will be preserved. For example,
let arr = ["a", "b", "c"]
let numArr = [1, 2, 3, 4]
for (let element of numArr) {
arr.push(element)
}
console.log(arr)
// [ 'a', 'b', 'c', 1, 2, 3, 4 ]
If we are adding the elements via the unshift
method, then in each iteration of the loop, the element we are iterating over will be added to the beginning of the array. So, the original order will be reversed. For example,
let arr = ["a", "b", "c"]
let numArr = [1, 2, 3, 4]
for (let element of numArr) {
arr.unshift(element)
}
console.log(arr)
// [ 4, 3, 2, 1, 'a', 'b', 'c' ]
Perhaps a visual may help you step through the loops and see what is happening.
-
Go to https://pythontutor.com/javascript.html
-
Copy & Paste the first code in this post (the one with push
) into the editor and click the “Visualize Execution” button.
-
Keep clicking the “Next” button till you reach the end of your code. In particular, pay attention to how the elements are being pushed to the arr
array.
-
Now do the same with the second code in this post (the one with unshift
). In particular pay attention to how the elements are being added to the arr
array and why this causes the reverse order.