@hafidzamr_
BlogExperience

Mutable and Immutable in JavaScript

January 27, 2023

-

3 min read

What is Mutable and Immutable?

Mutable and Immutable are two terms that are often used in programming. But what is the difference between them? In this article, I will explain the difference between mutable and immutable.

image

Mutable (Pass by Reference)

Mutable is a term that is often used in programming. Mutable means that the value of a variable can be changed. data type in JavaScript that is mutable is Array and Object. For example, if we have an array x with the value [1, 2, 3], then we can change the value of x to [4, 5, 6] or [7, 8, 9] and so on. The value of x can be changed.

Example

  • Array
let x = [1, 2, 3];
let y = x;

y.push(4);

console.log(x); // [1, 2, 3, 4]
console.log(y); // [1, 2, 3, 4]

on the code above, we have a variable x with the value [1, 2, 3]. Then we create a variable y and assign the value of x to y. Then we push the value 4 to y. Then we print the value of x and y. The value of x is [1, 2, 3, 4] and the value of y is [1, 2, 3, 4].

  • Object
let x = { name: 'John' };
let y = x;

y.age = 20;

console.log(x); // { name: 'John', age: 20 }
console.log(y); // { name: 'John', age: 20 }

on the code above, we have a variable x with the value { name: 'John' }. Then we create a variable y and assign the value of x to y. Then we add a property age with the value 20 to y. Then we print the value of x and y. The value of x is { name: 'John', age: 20 } and the value of y is { name: 'John', age: 20 }.

Immutable (Pass by Value)

Immutable is a term that is often used in programming. Immutable means that the value of a variable cannot be changed. primitive data type in JavaScript that is immutable is Number, String, Boolean, Null, Undefined, and Symbol

Example

  • Number
let x = 1;
let y = x;

// reassign the value of y
y = 2;

console.log(x); // 1
console.log(y); // 2

on the code above, we have a variable x with the value 1. Then we create a variable y and assign the value of x to y. Then we assign the value 2 to y. Then we print the value of x and y. The value of x is 1 and the value of y is 2.

  • String
let x = 'Hello';
let y = x;

// reassign the value of y
y = 'World';

console.log(x); // Hello
console.log(y); // World

on the code above, we have a variable x with the value Hello. Then we create a variable y and assign the value of x to y. Then we assign the value World to y. Then we print the value of x and y. The value of x is Hello and the value of y is World.

and so on.

Conclusion

if we take a look at above difference between mutable and immutable, when we change the value of variable y on mutable, the value of variable x will also change. But when we change the value of variable y on immutable, the value of variable x will not change.