Pass by value and pass by reference in JavaScript

Yahya Gok
3 min readAug 10, 2021

in JavaScript Arrays and Objects pass by reference. Everything else like strings, integer, number pass by value.

Passing by value means copying the data. However, Passing by reference doesn’t copy the data. With passing by reference we still pass the data by value but that value is reference to that data.

Let’s explain by Reference first;

So, we have a person object and this object has 3 properties,

name, age and occupation.

and then let’s create a function decode this function only console.log to the data that we pass.

So when we call the function with passing the data that we created which name is person.(in the below picture) The result will be the same object as we created.

For now everything is what we expected. Now, let’s modify our person object with name property a.name = ‘Michael’ inside the function.

The result will be changed to this;

Name property has changed as we expected. How about person object ? has anything changed over there ?

Maybe you would not expect that name property will change for person, because we only modified the function’s object. However, that reference also changed our main person object.

Above picture’s last lane shows that person object has modified to name: ‘Michael’ as well. The reason for this is in objects data pass by reference. Object and Arrays pass by reference in JavaScript.

When we do the same thing for array, we will get the same result. Here in this below picture has one arr = [10, 20, 30]

and the decode function pushes 70 into the array. and When we run the function with decode(arr), we will get [10,20,40,70]. when we also console.log(arr) will wwe get the same result, we will see that 70 over there too.

Data pass by Value

In the below picture, that is example for pass by value.

We have a number, it is 12, which is an integer, integer pass by value. Also, string pass by value. Here, we do have a function and this function changes the number to 30. When we run decode(num), this function will give us number 30, when we console.log(num), this will give us 12. Integer pass by value, it doesn’t modify the num. Here we pass the data by value.

Resources

--

--