OneCompiler

Value vs Reference in JavaScript

In JavaScript, we have 6 datatypes are available they are boolean, int, float, string, undefined, null. These all data types are called as Primitive data types.

In JavaScript, we have 3 types which are passed by reference they are array, function, and object. These are normally called as Objects.

Primitive types:

Primitive type holds the value of a variable which is assigned to it.

var num = 10;
var str = 'abc';
var x = null;

when we assign these variables using '='(Assignment operator) it actually stores the value.

var num = 10;
var str = 'abc';
var cpy = num;
var newStr = str;

console.log(num, str, dup, newStr); // output 10, 'abc', 10, 'abc'

If we see the above code both num and cpy has value 10 and str and newStr has a string abc.

As we discussed earlier primitive type variables stores values so if we change any values it doesn't affect the original variable.

For example:

var num = 10;
var str = 'abc';
var cpy = num;
var newStr = str;

cpy = 8;
newStr = 'xyz'

console.log(num, str, dup, newStr); // output 10, 'abc', 8, 'xyz'

So there will be no relationship maintained in primitive types.

** Objects:**

Reference type variables will store the address of the variables. So it maintains a relationship between the variable. It doesn't store the values of the variable as primitive.

When we create an array/object it will create somewhere in the system. As we discussed earlier array is a reference type arr variable will store the address. when we push or trying to modify an array, the compiler goes to the location of arr in memory and manipulates the array information stored there.

** Storing by Reference**:

Reference type will not store value but it stores the address of the variable. When we assign an array to another array using assignment operator it will store the address of the original array.

let ref = [1];
let refCopy = ref;

Now ref and refCopy variables have the address of the array. Which means that if we change ref variable, those changes will be available in refCopy.

ref.push(2);
console.log(ref, refCopy); // output [1, 2], [1, 2]

But this will not happen if we reassign a variable to that object.

For example, if there is an object

var firstObj = { name: 'madhav' };

and if we reassign this variable then it will not modify the actual object

var firstObj = { name: 'Madhav' };
firstObj = {nick: 'Nani'}

When we reassign the object address of the new object will be referred to the variable. The first object is still available in the memory but there is a reference variable assigned to it so garbage collector will delete this object.