Javascript - Primitive And Reference Values Assignment

Introduction

Primitive and reference values act differently when copied from one variable to another.

When a primitive value is assigned from one variable to another, the value stored on the variable object is created and copied.

Consider the following example:

var num1 = 5;
var num2 = num1;

Here, num1 contains the value of 5. When num2 is initialized to num1, it also gets the value of 5.

This value is separate from the one that is stored in num1, because it's a copy of that value.

When a reference value is assigned from one variable to another, the value stored on the variable object is copied.

This value is actually a pointer to an object.

Two variables point to exactly the same object, so changes to one are reflected on the other:

var obj1 = new Object();
var obj2 = obj1;
obj1.name = "First";

console.log(obj2.name);    //"First"

In this example, the variable obj1 is filled with a new instance of an object.

This value is then copied into obj2, meaning that both variables are now pointing to the same object.

When the property name is set on obj1, it can later be accessed from obj2 because they both point to the same object.

Related Topic