JavaScript (JS) is also a functional programming (FP) language. One of the core concepts of FP are immutable objects that has lots of benefits for other programming paradigms, e.g. object-oriented programming (OOP), too.

In this article I’ll explain to you the different types of immutable objects and how to achieve immutable objects in JavaScript.

Let’s start with mutable objects first: A mutable object is an object that can be modified after it is declared. For example foo is a mutable object:

let foo = {
    a: "b"
};
let bar = foo;
bar.a = "c";
console.log(foo.a); // c

By default custom objects in JS are mutable. The issue with mutable objects is that changing a value of the object propagates to all its references. This is known as side-effects and can lead to hard to debug errors.

An immutable object on the other hand is an object which can not be changed after it is declared. By default Math, Date, Numbers and Strings are immutable in JS, meaning you can’t delete, add, or overwrite their properties. For example you want to concatenate the string Hello with world like so:

let foo = "Hello" + "world";
console.log(foo); // Hello world

The String Hello was not modified. Instead a new String was created. The original Hello is left unchanged.

#functional #immutability #functional-programming #immutable #javascript #function

What people don’t know about immutable objects in JavaScript
1.10 GEEK