Difference between copy by value and copy by reference.

In JavaScript

Ravi Teja Perikala
1 min readDec 16, 2020

Copy by value:

In copy by value, a function is called by directly passing the value of the variable as the argument. Changing the argument inside the function doesn’t affect the variable passed from outside the function.

Example:

let a = 1;
function change(val)
{
val = 2;
}
change(a);
console.log(a);

Output : 1

In the above example, ‘a’ is assigned with value 1 and it has been passed to function ‘change’ and value is updated to 2 inside the function. As copy by value is used here, the value of ‘a’ is not changed and the output is 1.

Copy by reference:

In copy by reference, the address is passed instead of arguments to call a function. Due to this, changing the value inside the function affect the variable passed from outside the function. In JavaScript mostly arrays and objects follow copy by reference.

Example:

let a = { name : “Ravi”};
function change(val)
{
val.name=”Teja”;
}
change(a);
console.log(a);

Output: {name: “Teja”}

In the above example, an object named ‘a’ is declared outside the function ‘change’ and when we pass the object to the function, only the reference of the object is passed and when we changed the value, the value in the object outside function also got changed as both the variables are pointing to same object. This is an example of copy by reference.

--

--