DEV Community

Cover image for How Pass By Value and Pass By Reference works?
Lawaanu Borthakur
Lawaanu Borthakur

Posted on • Updated on

How Pass By Value and Pass By Reference works?

Javascript uses Pass By Value for primitive data types and Pass By Reference for objects.

This is one of the very important concept in JavaScript. So, let us understand it with some examples.

Pass By Value

In pass by value, the function is called by directly passing the value of the variable as argument and changing the argument inside the function does not affect the value of variable passed from outside the function.

function PassByValue(numOne, numTwo) { 
    console.log("Inside PassByValue Function"); 
    numOne = 300; 
    numTwo = 600; 
    console.log("numOne =" + numOne +" numTwo =" +numTwo); 
  } 
  let numOne = 12; 
  let numTwo = 23; 
  console.log("Before PassByValue Function"); 
  console.log("numOne =" + numOne +" numTwo =" +numTwo); 
  PassByValue(numOne, numTwo) 
  console.log("After PassByValue Function"); 
  console.log("numOne =" + numOne +" numTwo =" +numTwo); 

Enter fullscreen mode Exit fullscreen mode

Output:

Before PassByValue Function
numOne =12 numTwo =23
Inside PassByValue Function
numOne =300 numTwo =600
After PassByValue Function
numOne =12 numTwo =23
Enter fullscreen mode Exit fullscreen mode

In the above example we can see that the value of numOne and numTwo remains same after the function is called.

Pass By Reference

In Pass By Reference, Functions are called directly by passing the reference/address of the variable as argument. Changing the argument inside the function affect the value of the variable passed from outside the function.

function PassByReference(Obj) { 
    console.log("Obj,Inside PassByReference Function"); 
    Obj.num=44
    console.log(Obj); 
  } 
  let Obj ={num:12}; 
  console.log("Obj,Before PassByReference Function"); 
  console.log(Obj); 
  PassByReference(Obj) 
  console.log("Obj,After PassByReference Function"); 
  console.log(Obj); 
Enter fullscreen mode Exit fullscreen mode

Output:

Obj,Before PassByReference Function
{ num: 12 }
Obj,Inside PassByReference Function
{ num: 44 }
Obj,After PassByReference Function
{ num: 44 }
Enter fullscreen mode Exit fullscreen mode

In the above example we can see that the value of Obj changed after the function is called.

In summary, JavaScript primitive data types are passed by value, while non-primitive data types (objects and arrays) are passed by reference.

Wrap Up!!

I hope you enjoyed this article. Thank you for reading. Please share it with your network.

Top comments (0)