Blog

variables

JS

Copy By Value vs Copy By Reference

Copy By Value vs Copy By Reference in JS

Ilavenil Diagarajane

Ilavenil Diagarajane

Oct 7, 2022 ยท 2 min read

In JavaScript, when a function is called, the arguments can be passed in two ways.

  1. Copy By Value
  2. Copy By Reference

Primitive data types such as string, number, null, undefined and boolean follow copy by value in Javascript. Furthermore, Primitives are immutable.

  • In Pass by value, the function is called by directly passing the value of the variable as an argument.

  • So any changes made inside the function do not affect the original value.

  • The original value and the copied value are independent of each other as they both have a different space in memory.


_11
//JS copy by value
_11
function copyByValue(x) {
_11
x = x + x;
_11
return x;
_11
}
_11
_11
var y = 10;
_11
var result = copyByValue(y);
_11
_11
console.log(y); // 10 -> there is no change in orginal value
_11
console.log(result); // 100

Non-primitive data types such as objects, arrays, and functions follow copy by reference in Javascript. Furthermore, Non-primitives are mutable.

  • In Pass by Reference, Function is called by directly passing the reference/address of the variable as an argument.

  • So changing the value inside the function also change the original value.

  • JavaScript does not create a new space in the memory, instead, we pass the reference/address of the actual parameter.


_9
function copyByReference(varObj) {
_9
console.log("Inside Call by Reference Method");
_9
varObj.a = 100;
_9
console.log(varObj);
_9
}
_9
_9
let Obj = {
_9
a: 1,
_9
};


_2
console.log("Before copy By Reference Method");
_2
console.log(Obj); // {a: 1}


_2
copyByReference(Obj); // {a: 100}
_2
// Inside Copy by Reference Method


_2
console.log("After Copy by Reference Method");
_2
console.log(Obj); // {a: 100}


_16
let originalArray = [1, 2, 3, 4];
_16
_16
function pushArray(tempArray) {
_16
console.log("Inside Call by Reference Method");
_16
tempArray.push(5);
_16
console.log(tempArray);
_16
}
_16
_16
console.log("Before copy By Reference Method");
_16
console.log(originalArray); // [1,2,3,4]
_16
_16
pushArray(originalArray); // [1,2,3,4,5]
_16
// Inside Copy by Reference Method
_16
_16
console.log("After Copy by Reference Method");
_16
console.log(originalArray); // [1,2,3,4,5]

@ragavkumarv
swipe to next โžก๏ธ