JavaScript uses pass by value if the argument passed to the function is a primitive variable or primitive value. But when the argument passed to the function is a reference variable or value, then JavaScript uses pass by reference. In other words, JavaScript decides whether it would use 'pass by value' or 'pass by reference' based on the argument passed to the function.
Note: If you are not familiar with the primitive and reference variables in JavaScript and the difference between them, then visit What are primitive and reference variables in JavaScript? to learn more.
In pass by value, JavaScript copies the values of the arguments to the function parameters. So, any changes that you make to the function parameters do not affect the original arguments passed to the function.
Note: Pass by value is also known as call by value.
Let's understand pass by value with the help of an example.
function swap(x, y){ let temp = x; x = y; y = temp; } let a=10, b=20; swap(a, b); console.log(a); //10 console.log(b); //20
In this example, a function swap()
is defined that accepts two parameters, x
and y
. This function swap the values of the arguments passed to it.
function swap(x, y){ let temp = x; x = y; y = temp; }
Two variables, a
and b
, are declared and initialized with a value of 10 and 20, respectively.
let a=10, b=20;
When the swap()
function is called by passing variables a
and b
, JavaScript copies the value of variable a
to the parameter x
and b
to the y
parameter.
swap(a, b);
The swap()
function swaps the value of x
and y
parameters. But this change is not reflected in variables a
and b
because there is no link between arguments and parameters.
console.log(a); //10 console.log(b); //20