Difference between Pass by Value and Pass by Reference in JavaScript.

Pass by Value

Primitive data types like String, Number, Boolean etc. are immutable or cannot be changed once defined. When you define a primitive data type memory is allocated to it. On assigning it to another variable it’s copied and another memory is allocated for the copy.

Let’s try to understand with the help of an example,

let a = 100;
let b = a;
a = 90;
console.log(a); // prints 90
console.log(b); // prints 100

As you can see in the above code, changing the value of a doesn’t affect the value of b, since a different memory is allocated to it on assignment.

You can also try passing the value to a JavaScript function. It also behaves the same way.

function modifyValue(param){
	param = 100;
}

function foo(){
	let a = 34;
	console.log(a); // prints 34
	modifyValue(a);
	console.log(a); // prints 34
}

foo();

foo method calls modifyValue with parameter a. Since it’s a pass by value, the change in param in modifyValue doesn’t affect the variable a in foo.

Pass by Reference

Objects in JavaScript are mutable or can be changed. When an object is defined, it’s stored in memory and a reference is assigned to the variable. If you try to pass the variable reference or assign the variable reference to another variable, it doesn’t create a new memory allocation but points to the same memory allocation.

For example,

let a = {'name' : 'Rohan', 'age' : 30};
let b = a;
a.name = 'Sam'; 
console.log(a); // prints {'name' : 'Sam', 'age' : 30}
console.log(b); // prints {'name' : 'Sam', 'age' : 30}

As seen in the above example, since both variables a and b points to the same object reference, hence any change in a updates b and vice versa.

Let’s look at how it behaves when used in JavaScript functions,

function modifyParam(param){
	param.age = 100;
}

function foo(){
	let a = {'age' : 34};
	console.log(a); // prints {'age' : 34}
	modifyParam(a);
	console.log(a); // {'age' : 100}
}

foo();

In the foo method we are passing the object variable a to the modifyParam method. Since the object is passed by reference, the change to the param parameter in modifyParam changes the parameter a in foo method.