Is Javascript pass by value or pass by reference?

Before we get into whether JS is pass by value or reference, let's see what those terms mean.

Pass by value: Let's say your friend has written some lecture notes and you got a Xerox of them, whatever modifications you make in yours will now not affect his and vice-versa this is called Pass by value, when you make a copy of the contents/value of one variable into another.

Pass by reference: If your friend created a google doc of the notes and gave u admin access to it and sent u the access link, this is called Pass by reference, here instead of making a copy of value, you create a copy of the address of a variable and pass this to another

And now to answer the question Javascript is pass by value

But.

You might encounter some situations where it acts like pass by reference. So let's elaborate on this Example 1 :

let a = 10
let b
b = a
console.log(b) //output is 10
a = a + 1
console.log(b) // output is still 10

This is a typical pass by value example, we see that even though the value of a is changed b remains unaffected as JS is pass by value.

Example 2:

let a = [1,2]
let b
b = a
console.log(b)  // output is [1,2]
a.push(3)
console.log(b)  // output is [1,2,3]

Why is pass by reference behavior being shown here? the change in a is being reflected in b as well

It is because in Javascript the primitive types (there are 7 of them Number, String, Boolean etc ) are pass by value.

Where as the reference types (objects,function, arrays etc. basically anything other than the primitive types) act as pass by reference because they pass the reference as a value. That was a mouthful let's try to explore further:

In Example 1 primitive types 'a' and 'b' store the value in memory as follows :

snip1.PNG

Whereas when we create a reference type ( say c= [1,2] ) the reference/address of the value is stored :

snip2.PNG

So in the Example 2 when we assigned b to a , a copy of the reference was created and assigned to b as follows:

snip3.PNG As both these references point to the same value when one is changed the other is changed as well.

In summary JS is pass by value , it appears to show pass by reference behaviour but this is only because it passes the reference as a value.

Note : If we were to assign a new object to b, then the reference value inside it would change and b would no longer be pointing to the same object.

let a = [1,2]
let b
b = a
console.log(b)  // output is [1,2]
a.push(3)
console.log(b)  // output is [1,2,3]
console.log(b===a) // return true
b = [1,2,3]
console.log( b === a) // returns false

snip4.PNG