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. 

JavaScript Objects Types


In JavaScript there are 3 ways you can create an Object. Examples as below,

var object1 =
{
    name: "Zack",
    age: 35
}

console.log("Object 1 Name: "+object1.name);

var object2 = new Object();
object2.name = "Zack";
object2.age = 35;

console.log("Object 2 Name: "+object2.name);

function Object3(name, age)
{
    this.name = name;
    this.age = age;
    this.getName =function () {
        return this.name;
    }
}
var object3 = new Object3("Zack", 35)
console.log("Object 3 Name: "+object3.getName());

object1.sex = "male";
object2.sex = "male";
Object3.sex = "male";// Value will be undefined for the Object
//Object3.prototype.sex = "male";

console.log("Object 1: "+ object1.sex);
console.log("Object 2: "+ object2.sex);
console.log("Object 3: "+ object3.sex);

The 3rd Type of Object is the most used type, since it is highly reusable.