Value and Reference Type

Value type in Javascript:

  • number
  • string
  • boolean
  • null
  • undefined

Reference type:

  • object
  • array

Let's understand the difference between these two with examples:

let tom = 10;

let copyTom = tom;

console.log(copyTom, tom)   // 10 10

copyTom = 20;

console.log(copyTom, tom)  // 20 10

When we change the value of copyTom the value of tom does not change because they are value type.

The case is different with reference type.

let person = {name: 'tom', age: 20};

let copyPerson = person;

console.log(copyPerson, person) // { name: 'tom', age: 20 } { name: 'tom', age: 20 }

copyPerson.name = 'Jerry';

console.log(copyPerson, person) // { name: 'Jerry', age: 20 } { name: 'Jerry', age: 20 }

As you can see when we change the value of copyPerson.name object the name of person also changes. This happens because both refer to the same object.

Same behaviour can be seen for arrays as well.

let person = ['tom', 'jerry'];

let copyPerson = person;

console.log(copyPerson, person) // ['tom', 'jerry']

copyPerson['1'] = 'Bob';

console.log(copyPerson, person) // ['tom', 'Bob']

What happens we we send object or array as parameters to function, Does it changes the orignal object or array as well. 🤔

Let's take an example

let person = { name: 'tom', age: 20 }

console.log(person) // { name: 'tom', age: 20 }

function changePersonName(person_param) {
    console.log(person_param) // { name: 'tom', age: 20 }
    person_param.name = 'jerry'
}

changePersonName(person)

console.log(person) // { name: 'jerry', age: 20 }

As you can see name of person is changed.

Same goes for array as well as you can see in the below example:

let person = ['tom', 'jerry'];

console.log(person) // ['tom', 'jerry']

function changePersonName(person_param) {
    console.log(person_param)   // ['tom', 'jerry']
    person_param[1] = 'bob'
}

changePersonName(person)

console.log(person) // ['tom', 'bob']