Reputation: 6313
Here is the code in question:
const array = [
1, 2, 3
]
array.map(item => {
item = item + 1
})
console.log(array)
I thought that the item
(first) argument in the map
method is a reference to the original item in the array, and that mutating it directly would change the contents of that first array... is that not true?
Upvotes: 2
Views: 2344
Reputation: 136208
map
function returns a new array, it does not change the original one.
item
is a local variable here in arrow function item => {...}
. The assignment item = item + 1
does not change the original element, it rather changes item
local variable.
If you'd like to change the elements forEach
function is more efficient because it does not create a new array:
array.forEach((item, index) => {
array[index] = item + 1;
});
Upvotes: 4
Reputation: 13346
Your array contains primitives type elements (integer here). Variables of type primitive cannot be mutated by its reference. Mutating is possible if for example elements of your array are objects, like below:
var array = [{val: 1}, {val: 2}, {val: 3}];
array.map(item => {item.val = item.val + 1});
console.log(array);
Upvotes: 5
Reputation: 1383
Mozilla says;
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
So, map function doesn't mutate values of the array.
I know you don't want to this, but you can use this:
const array = [
1, 2, 3
]
array.map((item, k) => {
array[k] = item + 1
})
console.log(array)
Upvotes: 1