0
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?

4
  • 3
    Javascript callstack is single thread, so there would not be such a case asyncFunction happens to update the array while map is still running Commented Dec 29, 2021 at 14:35
  • 2
    nothing. its already run. Commented Dec 29, 2021 at 14:35
  • 1
    …and anyway, you're not updating the array, you're updating the arr variable. map is getting called on an object, and it will continue working with that object, regardless what happens to the variable where that object was looked up from originally. Commented Dec 29, 2021 at 14:46
  • async aside, you could explicitly change window.arr inside the map and it wouldn't affect the outcome of the call. Commented Dec 29, 2021 at 15:02

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.