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.
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:
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.
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.
Finally, the value of the y
variable does not change after the square()
function completes.
If JavaScript uses passing by reference, the value of the variable y
would change to 100
.
It’s obvious to see that primitive variables are passed by values. However, it is not the case for objects. Take this for example: