JavaScript Pass by Value and Reference, The Difference?

Pass by Value

In JavaScript, when the value of a variable is a primitive type, it is pass by value.

When the variable being passed is a primitive type🔗, what gets passed is a copy of the value, not the memory location of the variable. We can use = to assign a value to a variable. For example, assigning different numbers to a and b:

const a = 1;
const b = a + 1;

Notice in line 2, b is assigned the value of a + 1, so b will be 1 + 1 = 2. This is very intuitive and easy to understand; this is what is known as “pass by value.”

Pass by Reference

In JavaScript, when the variable is not a primitive type, it is pass by reference.

When a variable is an object or an array, JavaScript needs to keep track of its memory location, so what is stored in the variable is not the actual content, but the memory location of that content. For example, in the following diagram, the variable b actually holds the memory address:

const a = 1;
const b = [1, 2];
VariableValue
a1
b0x01
Memory AddressValue
0x01[1,2]

After understanding the concept of pass by reference, let’s extend the previous example. If we have a variable c = b, the diagram would look like this:

const a = 1;
const b = [1, 2];
const c = b;
VariableValue
a1
b0x01
c0x01
Memory AddressValue
0x01[1,2]

As a result, both b and c point to the memory location 0x01, so when we modify c, b will also change:

let a = 1;
let b = [1, 2];
let c = b;
b.push(3);
// Result: both b and c become [ 1, 2, 3 ]!

This is why the values of b and c both become [1, 2, 3], because b and c both point to the same memory location.

Equal but Not Equal

After understanding the difference between passing by value and passing by reference, we realize that memory locations and values are entirely different things; one is a pointer, and the other is the content, just like the example in the following chart.

const a = [1, 2];
const b = [1, 2];
console.log(a === b); // false
VariableValue
a0x01
b0x02
Memory AddressValue
0x01[1,2]
0x02[1,2]
let a = [1, 2];
let b = a;
console.log(a === b); // true
VariableValue
a0x01
b0x01
Memory AddressValue
0x01[1,2]

Summary

Understanding how JavaScript stores variables helps in better data manipulation, avoiding situations where modifying A inadvertently affects B.

References