Mozilla said:
map does not mutate the array on which it is called (although callback, if invoked, may do so).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Specifically, the third argument the callback was passed is:
The array map was called upon.
Which I assumed that means the array location in memory is copy into the callback by reference.
So by mutating the third argument, we should mutate the original array, but the following two pieces of snippet give conflicting result:
case 1, re-assigning the third argument did not mutate the original array:
var A = [1, 2, 3];
A.map((v,i,_A) => {
console.log("_A is the array map invoked on: ", _A===A); // true
_A = []; // reassign an empty array
return v;
});
console.log("'A' did not mutate:", A) // [1, 2, 3] did not mutate
case 2, setting the third argument to length of zero mutates the original array:
var B = [1, 2, 3];
B.map((v,i,_B) => {
console.log("_B is the array map invoked on: ", _B===B); // true
_B.length = 0; // clearing the array by setting it zero length
return v;
});
console.log("'B' has mutated:", B) // [] mutated
Clearly in the second case the original array is mutated (the iterator only execute once). But what am I missing ? Why the conflicting result ?