In JavaScript, when a function is called, the arguments can be passed in two ways.
- Copy By Value
- Copy By Reference
Copy By Value
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_11function copyByValue(x) {_11 x = x + x;_11 return x;_11}_11_11var y = 10;_11var result = copyByValue(y);_11_11console.log(y); // 10 -> there is no change in orginal value_11console.log(result); // 100
Copy By Reference
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.
Object
Copy By Reference
_9function copyByReference(varObj) {_9 console.log("Inside Call by Reference Method");_9 varObj.a = 100;_9 console.log(varObj);_9}_9_9let Obj = {_9 a: 1,_9};
_2console.log("Before copy By Reference Method");_2console.log(Obj); // {a: 1}
_2copyByReference(Obj); // {a: 100}_2// Inside Copy by Reference Method
_2console.log("After Copy by Reference Method");_2console.log(Obj); // {a: 100}
Array
Copy By Reference
_16let originalArray = [1, 2, 3, 4];_16_16function pushArray(tempArray) {_16 console.log("Inside Call by Reference Method");_16 tempArray.push(5);_16 console.log(tempArray);_16}_16_16console.log("Before copy By Reference Method");_16console.log(originalArray); // [1,2,3,4]_16_16pushArray(originalArray); // [1,2,3,4,5]_16// Inside Copy by Reference Method_16_16console.log("After Copy by Reference Method");_16console.log(originalArray); // [1,2,3,4,5]