What is Pass by Value and Pass by Reference in JavaScript

Pass by Value literally means to create a new copy of existing value & Pass by reference means, point to the value which is already exist.

In order to understand above statement, first, we need to understand how Stack and Heap memory works. Let’s see.

Pass by Value

Pass by Value in JavaScript

In the above image, there are three sections. First is your JavaScript code, Second is Stack Memory and Third is Heap Memory. All primitive data types (String, Number, Boolean, NULL, Undefined & Symbol) values get stored in the Stack Memory.

When we have assigned value 5 to the variable val, you can see in the stack it is present with variable name.

On the next line, we have created new variable val2 and assigned val variable to it. In the stack, you can see val2 variable has value 5 now. So this is Pass by Value.

Assignment of val to val2 simply created copy of value for new variable val2.

On the next line, we are changing val2 value to 7. In the stack, you can see val2 has value 7 now. BUT, if you notice it is not affected/changed val variable value. Because val2 variable has separate/independent memory location in stack memory.

This is why, we say, primitive types are immutable. Means, we can’t modify their stack memory (eventually the value) once it is assigned.

Pass by Reference

Pass by Reference in JavaScript

In the above image, we have declared array. Array is an object type not primitive. In the stack memory you can see array name val BUT there is some different value (#943) with it.

That is actually a memory address of Heap Memory where the actual values has been stored for an array.

In the Heap memory section, you can see that address (#943) has values of val array.

On the next line in code section, we have created new variable val2. We have assigned val variable to the val2. In the stack memory you can see new val2 variable has been created and address of val is copied inside it.

This is called Pass by Reference. You can see that val variable has passed it’s address to val2 NOT values. Now, both val and val2 have same Heap Memory address so they both are pointing to the same location at Heap Memory.

On the last line in code section, we are updating val2 array value at position 1. After updation, in the Heap Memory, array has changed its value to 5 at one position.

Because of same memory address as val, the val2 array modification leads to change in the original values. Thus, both val and val2 arrays have new updated values.

Note: ‘After updation’ part shown in the above image is NOT the new Heap Memory location. It is just written there to show you an effect on original array after updation.

That’s it. We hope you understand the difference between both.

Categories js