A grand sand dune.
A grand sand dune.

Grasping JavaScript: Watch Out for this Object Trap

Adrian Bernardo
Jul 11 · 2 min read

There’s one thing about objects in JavaScript that everyone should watch out for. Although subtle, passing an object to a function can have very big side effects on your projects. Let’s look at an example.

const obj = { x: 2 };const foo = obj => {
var const = obj;
newObj.x = 3;
return newObj;
};
const obj2 = foo(obj);console.log(obj2.x) // 3
console.log(obj.x) // 3

This is a no-no. When invoking foo we indirectly also change obj.x's value and we don’t want that. We want to keep obj immutable so that if there’s another function that needs that obj.x's value, the current value will be passed and not the indirectly changed value made from foo.

foo causes the indirect change because JavaScript passes objects to functions as references to the object and doesn’t make a copy of the object.

One way to resolve the indirect change issue caused by foo is to use the Object.create() method. You can read more from the docs. In short, it creates a new object where the source object is the prototype.

const obj = { x: 2 };const foo = obj => {
const newObj = Object.create(obj);
newObj.x = 3;
return newObj;
};
const obj2 = foo(obj);console.log(obj2.x) // 3
console.log(obj.x) // 2

Also note that arrays are also objects in JavaScript and functions will also pass references to that array. One way to resolve that is by using .slice().

// Before
const arr = [1,2,3];
const fooArr = arr => {
const newArr = arr;
newArr.push(4);
return newArr;
}
const barArr = fooArr(arr);console.log(arr); // [1,2,3,4]
console.log(barArr); // [1,2,3,4]
// After
const arr = [1,2,3];
const fooArr = arr => {
const newArr = arr.slice();
newArr.push(4);
return newArr;
};
const barArr = fooArr(arr);console.log(arr); // [1,2,3]
console.log(barArr); // [1,2,3,4]

Hopefully this helps you out to understand why this happens in JavaScript or if you’re trying to figure out why this specific bug was happening.

Follow me on twitter!

Adrian Bernardo

Written by

JavaScript Everything 🎉