Home > front end >  es6 map if the array gets changed
es6 map if the array gets changed

Time:12-31

window.arr = [ 1, 2, 3, 4, 5 ];
window.arr.map(el=>{
    console.log(el);
});
asyncFunction(){
    window.arr = [ 2, 4, 6 ];
}

what will map do if asyncFunction happens to update the array while map is still running?

CodePudding user response:

First off Array.prototype.map() is entirely synchronous so the single threaded nature of Javascript will prevent your asyncFunction from running during the time that your windows.arr.map() is running.

But, even more interesting is that window.arr = [2,4,6] assigns a new array to the window.arr variable. That array has nothing at all to do with the array that .map() was working on. So, even if they could somehow be interwined, the .map() operation has its own array and it just keeps working on that array and that array has nothing to do with the new array that was put into the window.arr property.

Remember that a statement such as:

 window.arr = [2,4,6];

doesn't do anything to any array that was previously in window.arr. If anyone else has a reference to the prior array, that array will still exist just fine and be unaltered.

Here's a simple demonstration:

let a = [1,2,3];
let b = [4,5,6];
window.arr = a;
console.log(a);
window.arr = b;
console.log(a);

From this, you can see that array a was not changed at all when window.arr was reassigned. So, in your example, it was array a that .map() was running on.

  • Related