Skip navigation

Pass by value and pass by reference is age old concept. It is working similar way in JavaScript too. If you like to see some code so that you can understand better. Keep reading.

Brief theory before jump into code. JavaScript primitive types (string, number, boolean, null and undefined) are passed by value. Whereas non-primitive types (objects, arrays, functions, etc.) are passed by reference.

// Primitive types: Immutable by default
let x = 5
let y = x
y = 10
console.log(x) // output 5
console.log(y) // output 10

// Non-primitive types: Mutable
let animal = {
    name: 'Rat'
}
let anotherAnimal = animal
anotherAnimal.name = 'Horse'
console.log(animal) // {name: "Horse"}
console.log(anotherAnimal) // {name: "Horse"}
console.log(animal === anotherAnimal) // true

This knowledge might be useful while learning react.js, redux architecture.

Leave a comment