Javascript map will only shallow-copy your object

Hilal Arsa
2 min readSep 20, 2023

--

They do so by first constructing a new array and then populating it with elements. The copy always happens shallowly — the method never copies anything beyond the initially created array. (Array — JavaScript | MDN mozilla.org).

Above is what listed in the Array mutation documentation from MDN. We know that when running Javascript map function, it will :

(1) accept a function as argument

(2) invoke the function in every array iteration

(3) and return us back an array.

const originalArray = [1, 2, 3, 4, 5];

const newArray = originalArray.map(function(element) {
return element * 2;
});

console.log(originalArray); // [1, 2, 3, 4, 5]
console.log(newArray); // [2, 4, 6, 8, 10]

This new array is not referencing the old array we supplement in, but instead, it creates a new array, copy everything from old array to new array in every iteration, and return us the result.

But there’s important thing here that if not highlighted, can cause us very interesting bug that is quite difficult to find. Keyword : Object shallow copy.

Yep, if your old array has an object, the iteration on map — and any iterative methods — will copy the object to new array, but still kept the reference of the object to its old array.

Running and changing value inside map with refObj inside will mutate the content of refObj.
const originalArray = [{ name: "Alice" }, { name: "Bob" }, { name: "Charlie" }];

const newArray = originalArray.map(function(element) {
element.name = element.name.toUpperCase();
return element;
});

console.log(originalArray);
// [{ name: "ALICE" }, { name: "BOB" }, { name: "CHARLIE" }]
console.log(newArray);
// [{ name: "ALICE" }, { name: "BOB" }, { name: "CHARLIE" }]

Data mutation is sometimes bit tricky in Javascript. So be careful if we want to mutate the result of map that contains an object. Reference issue : javascript — Why does map mutate array of objects? — Stack Overflow

--

--