Here is an example
arr1 = [{ b: 2 }, { a: 1 }] // an array with 2 elements
arr1.forEach(function (element, index, array) {
console.log(element);
console.log('of');
console.log(array);
console.log('');
arr1.push({ c: 3 });
});
console.log(arr1);
Result
{ b: 2 }
of
[ { b: 2 }, { a: 1 } ]
{ a: 1 }
of
[ { b: 2 }, { a: 1 }, { c: 3 } ]
[ { b: 2 }, { a: 1 }, { c: 3 }, { c: 3 } ]
In above example I am traversing an array and adding more values to it and they are getting added in the original one while looping
Does forEach
use a different array to loop?
Modifying the array during iterationforEach() does not make a copy of the array before iterating.
forEach() does not mutate the array on which it is called.
forEach Loop It is a newer way with lesser code to iterate over an array. It is faster in performance. It is slower than the traditional loop in performance.
The forEach() method executes a function once for each item in the array. The method is called on the array object that you wish to manipulate, and the function to call is provided as an argument. In the code above, console.
It does not use a different array, as you can see, that when you console.log(array);
, you will still see the new elements, even though you pushed them onto arr1
.
So we know that array
and arr1
point to the same Array.
However what forEach
does, atleast according to the polyfill on MDN, is this:
Before iterating through it, it will extract the length of the Array, and only then start iterating. So if the length of the array changes inside the function you pass to forEach
, the iteration will not change.
// 2. Let lenValue be the result of calling the Get() internal
// method of O with the argument "length".
// 3. Let len be toUint32(lenValue).
var len = O.length >>> 0;
// 6. Let k be 0
k = 0;
// 7. Repeat, while k < len
while (k < len) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With