mutability pain in JavaScript

try predicting the output of the code below.

js

var obj = {a:1, b:2}
var func = function(_obj){ _obj.a = 5;  return _obj }
var obj2 = func(obj);
console.log(“old obj:: “,obj); console.log(“new obj:: “,obj2);

those who predicted that ‘old obj’ and ‘new obj’ will be different, you should read this post.

You might have thought that function ‘func’ will return a fresh copy of the object with 5 as the value of the key ‘a’, keeping the value of the key ‘a’ unaltered for the original object (here ‘obj’). Unfortunately, this is not the case. Arrays and objects are mutable in the JS arena. The actual output of the code above will be something like below:

—— actual output ——
old obj:: {a:5, b:2}
new obj:: {a:5, b:2}

this will become a pain while developing complex problems.

Sollution is pretty simple. just put your object within ‘JSON.parse(JSON.stringify(__anyObject__))’. This will indeed pass the same object. However, it will pass a fresh copy of a object and will not change the value of original object.

New code:

var obj = {a:1, b:2}
var func = function(_obj){ _obj.a = 5;  return _obj }
var obj2 = func(JSON.parse(JSON.stringify(obj)));
console.log(“old obj:: “,obj); console.log(“new obj:: “,obj2);

—— new output ——
old obj:: {a:2, b:2}
new obj:: {a:5, b:2}

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s