Learn immutability with JavaScript

const vs freezing, adding, removing, editing and immutable plain object and array

Cristian Salcescu
Frontend Essentials

--

Photo by the author

An immutable value is a value that, once created, cannot be changed.

Imagine you are waiting in queue. At entrance you got an electronic device showing your number. Just before you were very close to be served, your order number has changed on the screen. As you ask around why it happened, you understand that anyone in the building can change your number, but nobody knows who. While you are waiting, the order number continues to change, again and again. You now face the task of asking everyone in the building to stop changing your order number.

Back to code, imagine the order device as the order object with the number property. Imagine that the order.number property can be changed by any piece of code in the application. Detecting what part of the code did the change is hard. You may need to check all the code that uses the order object and imagine how it may happened.

An immutable order object will not have this kind of problems.

Immutability in general avoids a series of unexpected bugs hard to detect and reason about.

Primitives

--

--

Responses (12)