JavaScript Tutorial JavaScript References

JavaScript Functions - Pass by Reference



When the argument or parameter of a function is passed by reference, then the function takes the parameter as reference and any changes made to the parameter inside the function will change the parameter itself also. In JavaScript array and Object follows pass by reference property.

Example:

In the example below, the function called Square is created which takes an object as argument and changes it inside the function. When the passed object is printed before and after calling the function, the object gets changed.

function Square(obj) {
  obj.x = obj.x * obj.x;
  document.write("Value of obj.x inside function: ",
                  obj.x, "<br>");
}

let obj = {
  x: 5
}

document.write("Value of obj.x before passing to the function: ",
                obj.x, "<br>");

//calling the function
Square(obj);

document.write("Value of obj.x after passing to the function: ",
                obj.x, "<br>");

The output of the above code will be:

Value of obj.x before passing to the function: 5
Value of obj.x inside function: 25
Value of obj.x after passing to the function: 25

Example:

Similarly, when the passed array is printed before and after calling the function, it gets changed.

function PassByReference(Numbers) {
  Numbers.push(40);
  document.write("Numbers contains (inside function): ",
                  Numbers, "<br>");
}

let Numbers = [10, 20, 30]

document.write("Numbers contains (before passing to the function): ",
                Numbers, "<br>");

//calling the function
PassByReference(Numbers);

document.write("Numbers contains (after passing to the function): ",
                Numbers, "<br>");

The output of the above code will be:

Numbers contains (before passing to the function): 10,20,30
Numbers contains (inside function): 10,20,30,40
Numbers contains (after passing to the function): 10,20,30,40

❮ JavaScript - Functions