What is Immutability?

What is Immutability?

Ferenc Almasi β€’ 2020 November 12 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

Another core principle of functional programming is immutability. When we talk about immutable variables and objects, we simply mean that once declared, their value can’t be changed. This can reduce the complexity of your code and make your implementation less prone to errors.

To demonstrate immutability through an example, let’s say you have an array where you need to remove the first item. Take a look at the differences below:

Copied to clipboard! Playground
const presents = ['🎁', 'πŸ“¦', 'πŸŽ€', 'πŸ’', 'πŸŽ„'];

// --- Mutable solution ---

// we get back 🎁
// and presents will be equal to ['πŸ“¦', 'πŸŽ€', 'πŸ’', 'πŸŽ„'];
presents.shift();

// --- Immutable solution ---

// newPresents will be equal to πŸ“¦ πŸŽ€ πŸ’ πŸŽ„
// and presents will be still equal to ['🎁', 'πŸ“¦', 'πŸŽ€', 'πŸ’', 'πŸŽ„'];
const newPresents = presents.slice(1);
immutability.js

In the first example, we modify the original array with the shift function. If we want to achieve the same but keep the original array intact, we can use slice instead. This way you can avoid having unforeseen bugs in your application where you unintentionally modify data that should be kept in pristine condition.

One downside of immutability is performance. If you create too many copies you will run into memory issues so in case you operate on a large data set, you need to think about performance.

What is immutability in JavaScript?
If you would like to see more Webtips, follow @flowforfrank

Why Do You Need to Know About Functional Programming?

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.