Abhinav Rai

Javascript — Call by value or Reference?

Javascript uses a pass by value strategy for primitives but uses a call by sharing for objects. Call by sharing is largely similar to pass by reference in that the function is able to modify the same mutable object but unlike pass by reference isn’t able to assign directly over it.

Primitives in JS: Number (1,10), undefined , null , boolean and String.

What is Call by sharing?

In call by sharing, we can change the property of the object but not replace the object.

Eg:

function addToArray(arrayName, value) {arrayName.push(value);}
let arr = [1,2,3]
addToArray(arr, 4);
console.log(arr);
// [1,2,3,4]
// Property of array (push) being used

function changeArray(arrayName1) {arrayName1 = []}
changeArray(arr);
console.log(arr);
// [1,2,3,4] This is not []

How this internally works?

arr points to [1,2,3] when we say let arr = [1,2,3]. When we call function addToArray is creates another object (arrayName) which points to the same Array of [1,2,3];

We can access it’s properties or proto values(push, pop, etc) and also as arr points to the same object it’s value is also changed.

What happens when we call changeArray?

Another object arrayName1 is created just like arrayName which points to [1,2,3] but when we do arrayName1 = [] we cut the reference it has to [1,2,3] and assign this local variable a new value leaving the original value of arr as before.

You may contact the author on abhinav.rai.1996@gmail.com