Pass by Value, Pass by Reference

In JavaScript, There are two types of Data Types

  • Primitive Data Type (Pass by Value)

  • Non-Primitive (Pass by Reference ) / Object

Primitive Data Type:

  • null

  • undefined

  • string

  • number

  • boolean

  • symbol

These are Passed by value.

Non-Primitive / Object

  • Object

  • Array

  • Functions

These are Passed by reference.

Pass by Value

Every time you assign a value to a variable a new fresh copy is created.

// Pass by Value
// let's suppose

let a = 10;
let b = a;

// Here we're assigning variable a to variable b, making a fresh new copy of that variable
b = b + 10;

// a = 10
// b = 10

// So, if we make changes on variable b it does not affect variable a

Pass by Reference

When creating an object you're given a reference to that object. If 2 variables hold the same reference, then changing the object reflects in both variables.

// Pass By Reference

// Let's suppose we have an object with a couple of properties

const obj = {
  name: 'Pritam',
  age: 17,
};

// create one more object
const obj2 = obj;

// In the above case, we're coping obj to obj2
// In this case, the Reference of both objects points to only one object obj
// so if we make a change in obj2, it will also affect the obj

obj2.name = 'Rahul';

// Here you can see both have the same properties, which means both References point to one object

console.log(obj, obj2);

//{name: "Rahul", age: 17},{name: "Rahul", age: 17}

Comparison

var c = 1
var d = c

console.log(c === d)

// This will give you true, === operator evaluate according to the value, don't care about
// where the value was taken, both are point different memory location
 
let arr = [1];
let arr2 = [2];

console.log(arr === arr2);

// This gives you falsely because both are pointing to different Reference in the program
// But we Try to make a single Reference

let arr3 = arr

console.log(arr3 === arr)

// This will give you true because arr3, and arr both are pointing to the same reference

Last updated