In JS there are different ways how to create immutable objects. In this article I’ll explain to you the different types of immutable objects and how to achieve immutable objects in JavaScript.
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
<p>Other then the syntactical differences. The main difference is the way the this keyword behaves? In an arrow function, the this keyword remains the same throughout the life-cycle of the function and is always bound to the value of this in the...
The mystic term of Functional Programming (FP) must be familiar to any JS developer. The first impression when we say “JS supports functional programming paradigm”.
Let’s talk about the raw way of writing functions. Functions perform certain set of actions according to our requirements which could include fetching data, updating State, changing a set of mutable values and updating the DOM and so on.
Functional Programming: Higher Order Functions. A Better Take on JavaScript’s Higher Order Functions. Functional Programming is awesome! It makes programming fun.
Who else loves to write side-effects-free functions? I think we, as programmers, all do. Today, in this story, I will walk you through the basic principles of functional programming that will make your coding life easier.