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?
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?
-
5
ECMAScript 2015, 22.1.3.10 Array.prototype.forEach ( callbackfn ) -> Steps 3 and 8. The number of elements to visit is determined before the first call of
callbackfn
and not updated afterwards – Andreas Commented Aug 10, 2016 at 7:20 -
1
In
forEach
and in (possibly all) other array methods the index variable is not mutable and relies on the conditions the moment the method is invoked. Such as it will start from 0 and will increment up until the length of the array the moment it is invoked. It's fixed and even if you try to modify it in your callback like advancing, retarding or breaking in the middle... you can not unless you throw an exception. Plus there is no standard JS functionality to clone a deep copy of an object whatsoever. – Redu Commented Aug 10, 2016 at 7:53
2 Answers
Reset to default 5It 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) {
...
}
It does not create any copy of array. The reference to the original array is passed to the array argument of the forEach function. Kindly follow below link. http://jkoder./foreach-method-in-arrays-functional-programming-in-javascript-part-3/