JavaScript Pass by Value and Pass by Reference

JavaScript pass by value and reference; Through this tutorial, i am going to show you how to use pass by value and pass by reference in javaScript with the help of examples.

javascript pass by value and pass by reference is a simple difference. One is copied the argument value and stored in a new memory location. And the second one has stored a memory reference location of pass argument.

JavaScript Pass by Value and Pass by Reference

  • JavaScript Pass By Value
  • JavaScript Pass By Reference

JavaScript Pass By Value

In the javascript pass by value means, it copies the value of the argument does not affect or the relation between their memory location.

let x = 25 
let y = x
console.log(x) // => 25
console.log(y) // => 25
x = 15
console.log(x) // => 15
console.log(y) // => 25

In the above example, i have declared two variables named x and y. And assign variable x = 25, and Using the equals operator assign a value to variable x and it creates a new location in memory, points (x) to the address, and fills it with the value 25. After that, i declare a new variable name y and assign x value to y. It also creates a new location in memory, points (x) to the NEW address, and fills it with a copy of (a)’s value (25).

Next, The console.log() of each variable prints what i would expect 25 at this point.

However, change the value of variable x = 1 and console.log x and y variables x variable prints 1 as expected, but y variable is still equal to 25. Why?

Because i mentioned earlier, both the variable values stored in different memory location, So when i change x variable value, that’s time it does not effect y variable value. it has no idea that x variable value has changed since that is an entirely separate address in memory.

JavaScript Pass By Reference

JavaScript pass by reference means, it directly affects the memory location of argument, where the argument value is stored.

let x = {item: "Dell"}
let y = x
console.log(x) // => {item: "Dell"}
console.log(y) => {item: "Dell"}
x.item = "HP"
console.log(x) // => {item: "HP"}
console.log(y) // => {item: "HP"}

In the above example, i have created a two-variable named x and y. Create x variable and assign a javascript object value to it. After that, assign x variable to y variable. When assigning object values, it will create a new spot in memory. The objects which will be assigned to y variable to the same location in memory, where x variable object is stored in memory.

Next print both the variable x and y.

So when i change x variable objects value. And when console.log() of both x and y variable. They are print the same result.

More JavaScript Tutorial

Recommended:-JavaScript Arrays

Be First to Comment

Leave a Reply

Your email address will not be published.