Difference pass by reference or pass by value

Before discussing into JavaScript pass-by-reference or pass-by-value function, it is known about the difference between primitive and non-primitive.

Primitive Values: – Data Types string, number, null, undefined, symbols, and Boolean are primitive values. Primitive values are passed by value in JavaScript.

Non Primitive Values: – object, array, and function are non-primitive values. All objects and functions are passed by reference in JavaScript.

Pass by Value: –

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

Pass by value creates a new space in memory and makes a copy of a value.

All JavaScript arguments are always passed by value.

When we assign a variable in primitive type value, we create a variable item1 space location/address in the memory (let’s say 1005), and another creates a new variable item2 (let’s say 1010) and assign the value of the previous variable item1, the equal (=) operator creates new space in the memory which is dependent or previous variable item1 and address 1005 and copy (item1) new create space in the memory.

Example:

let item1 = 10

let item2 = num1

console.log(item1) // 10

console.log(item2) // 10

num1 = 20

console.log(item1) // 20

console.log(item2) // 10

Pass by reference:- 

In JavaScript pass by reference, a function is called by directly passing the reference/address of the variable as the argument.

In JavaScript objects and arrays are passed by reference.

Pass by reference does exactly the value stored in memory get referenced?

 

Example:-

let Obj = {

name: "ajay",

roll_no:8,

topic: "JavaScript"

};

 

function callByReference(item) { 

  item.roll_no = 5; 

  console.log(item.roll_no); 






console.log(Obj.roll_no);    //  8

callByReference(Obj);             // 5

console.log(Obj.roll_no);    //   5

Summary:-

  1. In JavaScript, we have call-by-value also called primitives and call-by reference is non-primitives which are objects, and arrays.
  2. In JavaScript Pass by value, a copy of the original variable is created.
  3. In pass-by-reference, no copy is created in the memory.
  4. Passes all arguments to a function by values.

Leave a Reply