Immutability

Primitive

  • Primitives, like strings and numbers, are immutable by default

let greet = "Hello";
greet += "World";  
console.log(greet); // Hello world
  • Even if it is tried to be changed, new value with different memory address will be created instead of changing its original value

  • For function call , primitive input is immutable

let test = "Hello";
const testFn = (input) => {
    test += "World";
}
testFn(test);
console.log(test) // Hello

Array & Object

  • Array and object are mutable

// Array
let ages = [42, 22, 35];
ages.push(8);  
console.log(ages); // 42, 22, 35, 8

// Object
let p = {name:"Nee", age: 30};
p.age = 31;
console.log(p); // {name: "Nee", age:31}
  • For function call , they are mutable

let test = ["Hello"];
const testFn = (input) => {
    test.push("World");
}
testFn(test);
console.log(test) // [Hello, World]

let test2 = {key:"Hello"};
const testFn = (input) => {
    test2.key = "World";
}
console.log(test2); // {key: World}
  • However, it is recommended to use immutable pattern for best practice to prevent from any side effect

// Array
let test = ["Hello"];
test = [...test, "World"];
// Object
let p = {name:"Nee", age: 30};
p = {...p, age: 31};
console.log(p);

Last updated

Was this helpful?