Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does forEach create a deep copy of array before looping?

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 forEachuse a different array to loop?

like image 888
Vikas Bansal Avatar asked Aug 10 '16 07:08

Vikas Bansal


People also ask

Does forEach create a copy?

Modifying the array during iterationforEach() does not make a copy of the array before iterating.

Does forEach change the original array?

forEach() does not mutate the array on which it is called.

Is forEach better than for loop?

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.

What does the forEach method do?

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.


1 Answers

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) {
    ...
}
like image 68
Luka Jacobowitz Avatar answered Oct 26 '22 15:10

Luka Jacobowitz