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?
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?
-
If you want to mutate each item in an array, you would use 'forEach' and then call a mutating method on each element. When you do
item = item+1
, you're not mutatingitem
regardless of if you call.map
or.forEach
, because you're just reassigning a local variable. – TKoL Commented Jan 9, 2018 at 11:04
3 Answers
Reset to default 5Your 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);
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;
});
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/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)