What is call by value and call by reference in JavaScript?

know the difference between call by reference and call by value.

Table of contents

No heading

No headings in the article.


Firstly, what do you think the result of this code:

var x=5;

var z=x;

console.log("x=" ,x , "z=",z);

Simply, it's 👇:

  Output
  x=5 , z=5

If we change only the value of x, what do you think the output is?

  x=7;

  console.log("x=" ,x , "z=",z);

   //Output
  //x=7 , z=5

Why only x is changed, and z is still 5?

Because this is call by value, when we assign x=z, the values are copied and saved in different locations in memory, so when one parameter changes don't affect the other one, this happened only in primitive variables " Number, String, Null, Undefined, Boolean, Bigint".

But in "Object, Arrays" Non-primitive data type, when we create object variable, and assign this object to new variable, no new object is created, both objects have the same location in the memory, changes one object change the other, these is call by reference, each object refers to the other👇:

 var arr1=[1,2,3,4];

//call by reference 
   var arr2=arr1;

  console.log("arr1=",arr1 , "arr2=",arr2);

  //output
  //arr1=[1, 2, 3, 4] , arr2=[1, 2, 3, 4]

//Change the frist array change both
  arr1[0]=9;

    console.log("arr1=",arr1 , "arr2=",arr2);

  //output
  //arr1=[9, 2, 3, 4] , arr2=[9, 2, 3, 4]

  //Chnge the second array too, change both
  arr2[0]=1;
    console.log("arr1=",arr1 , "arr2=",arr2);

  //output
  //arr1=[1, 2, 3, 4] , arr2=[1, 2, 3, 4]

For more explain say this is the memory 👇

We define a variable x and assign its value to z, so this creates two different variables in different locations in the memory👇

We define a variable x and assign its value to z

When we change one variable this has no effect on the other variable👇

When we change one variable this has no effect on the other variable

But this different in refer two objects or arrays, they share the same location in the memory, so any changes affect both👇

But this different in refer two objects, they share the same location in the memory, so any changes affect both👇

I hope that I have succeeded in my explanation and thank you, keep in touch @ismailabualmagd