Javascript Reference values vs Primitive values: Copying Values

Introduction

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

When a primitive value is assigned, the value is copied for the new variable.

Consider the following example:

let num1 = 5;
let num2 = num1;

Here, num1 contains the value of 5. When num2 is initialized to num1, it 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, the value is also copied.

The difference is that this value is actually a pointer to an object.

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

                                                                                           
let obj1 = new Object();                                                                        
let obj2 = obj1; 
obj1.name = "HTML";                                                         
                                                                            
console.log(obj2.name);  // "HTML" 
                                                                            

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.




PreviousNext

Related