JavaScript pass by value or pass by reference

In JavaScript, all function arguments are always passed by value. It means that JavaScript copies the values of the passing variables into arguments inside of the function.

Any changes that you make to the arguments inside the function does not affect the passing variables outside of the function. In other words, the changes made to the arguments are not reflected outside of the function.

If function arguments are passed by reference, the changes of variables that you pass into the function will be reflected outside the function. This is not possible in JavaScript.

Passing by value of primitives values

Let’s take a look at the following example.

function square(x) {
    x = x * x;
    return x;
}
var y = 10;
var result = square(y);
console.log(y);// 10 -- no changeconsole.log(result);// 100
Code language: JavaScript (javascript)

How the script works.

First, define a square() function that accepts an argument x . The function changes the value of the x argument.

Next, declare the variable y and initialize its value to 10:

https://www.javascripttutorial.net/wp-content/uploads/2016/08/JavaScript-Pass-By-Value-declare-variable.png

Then, pass the y variable into the square() function. When passing the variable y to the square() function, JavaScript copies the value of y to the x variable.

https://www.javascripttutorial.net/wp-content/uploads/2016/08/JavaScript-Pass-By-Value-passing-primitive-argument.png

After that, the square() function changes the x variable. However, it does not impact the value of the y variable. This is because x and y are totally different variables. They have no link.

https://www.javascripttutorial.net/wp-content/uploads/2016/08/JavaScript-Pass-By-Value-changing-primitive-value.png

Finally, the value of the y variable does not change after the square() function completes.

https://www.javascripttutorial.net/wp-content/uploads/2016/08/JavaScript-Pass-By-Value-primitive-type.png

If JavaScript uses passing by reference, the value of the variable y would change to 100.

Passing by value of object

It’s obvious to see that primitive variables are passed by values. However, it is not the case for objects. Take this for example: