Avoid mutating your JS objects!

JavaScript objects are passed by reference! Let’s jump right into an example.

var Friend = function (name, age, hobby) {
this.name = name,
this.age = age,
this.hobby = hobby
};
var sara = new Friend('Sara', 25, 'coding');
output: {name: "Sara", age: 25, hobby: "coding"}

Awesome! We’ve made a new instance of Friend. Now I want to make another friend with a different name, but with the same age and hobby.

var blondie = sara;
blondie.name = 'Blondie';
// console.log(blondie)
output: {name: "Blondie", age: 25, hobby: "coding"}

Great — a bit of a short cut and exactly what we wanted… right?

// console.log(sara)
output: {name: "Blondie", age: 25, hobby: "coding"}

Noooo! Now sara is assigned with the name “Blondie”. Why did this happen? It’s simply because objects are passed by reference. To prevent this, let’s explore the Object.assign() method.

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object. (MDN)
Object.assign(target, ...sources)

Let’s rewind. We do not want to mutate sara so let’s make a copy instead with Object.assign()

var blondie = Object.assign({}, sara, {name: 'Blondie'});
// console.log(blondie)
output: {name: "Blondie", age: 25, hobby: "coding"}
// console.log(sara)
output: {name: "Sara", age: 25, hobby: "coding"}

Success! Now Blondie who is the same age and has the same hobby as Sara is created with ease.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.