Describe pass by value and pass by reference in JavaScript?


Pass by value 

In pass by value, a function is called by directly passing the value of the variable as the argument. Changing the argument inside the function doesn’t affect the variable passed from outside the function. Javascript always pass by value so changing the value of the variable never changes the underlying primitive (String or number).

In the following example, variable 'a' has assigned value 1. But inside function 'change' it got assigned with value 2. Since javascript is always a pass by value, the displayed output will be '1' but not '2'.

Example

Live Demo

<html>
<body>
<script>
   let a = 1;
   let change = (val) => {
      val = 2
   }
   change(a);
   document.write(a);
</script>
</body>
</html>

Output

1

Pass  by reference

There are some instances that address is passed instead of arguments to call a function. At that time, changing the value inside the function affect the variable passed from outside the function. This is called a pass by reference. In javascript mostly arrays and objects follow pass by reference.

In the following example an object named 'a' is declared outside the function 'change'. Here one should heed that variable 'a' got mutated but not assigned with value 2, as shown in example 2. A pass by reference takes place when mutation has occurred.   

Example-1

Live Demo

<html>
<body>
<script>
   let a = {num:1};
   let change = (val) => {
      val.num = 2
   }
   change(a);
  document.write(JSON.stringify(a));
</script>
</body>
</html>

output

{"num":2}


In the following example instead of mutation, variable 'a' got assigned with value 2. So pass by value takes place and there will be no affect on outside variable.

Example-2 

Live Demo

<html>
<body>
<script>
   let a = {num : 1};
   let change = (val) => {
      val = {num :2};
   }
   change(a);
   document.write(JSON.stringify(a));
</script>
</body>
</html>

output

{"num":1}
raja
Published on 14-Jun-2019 17:09:16
Advertisements