Showing posts with label Immutable. Show all posts
Showing posts with label Immutable. Show all posts

Sunday, December 16, 2018

JavaScript Mutable and Immutable Objects



In JavaScript Primitives are immutable, which means that the value is passed instead of reference.
For Objects the reference is passed instead of value. Example as below,

//Primitives are immutable
var a = 10;
var b = a;

console.log("a: "+a);
console.log("b: "+b);

a =20;

console.log("a: "+a);
console.log("b: "+b);

//Mutable
var c = {name: "Zack"};

var d = c;
console.log("c: "+c.name);
console.log("d: "+d.name);
d.name = "Arnold";
console.log("c: "+c.name);
console.log("d: "+d.name);

Ensure whether you are passing value or reference during development. This is one of the basic concepts in JavaScript.