I do not really understand how such objects can be used. As a "constant"? But when do you need such an object?

The quote from the wiki also does not give clarity:

In programming, immutable (English immutable) is an object whose state can not be changed after creation.

I would like to see an example of real use.

Important - I would like to see a JS example.

  • Possible duplicate question: immutable-objects and multithreading - Vladimir Glinskikh
  • @ Vladimir there java. I want a JS example. - Ilya Bizunov
  • Check out the React and Redux libraries. They are built around immutable objects. - Pavel Mayorov

1 answer 1

Imagine that you are making a drawing program that has the functionality of "step-by-step return actions". But in order to go back a step you need to have a copy of the program at that very moment. Therefore, you create components that store their state in objects called ValueObject . After doing something, you need to go through the whole program and collect these objects, and then save it in some kind of storage, for example an array. But there is one problem - in javascript non-primitive types are passed by reference. That is, you drew the first shape and saved the information models into an array. After the second figure was drawn, all information models changed. But they have changed not only in the components, but also in the very array in which we saved the data after drawing the first shape. Everything, the program has broken!

To solve this problem, and came up with an approach in which objects are created new each time and do not change as the program changes.

Still very often they give us an example of convenience when debugging, but in my opinion, modern debuggers do the same thing, showing a change in the program by layers. The convenience of testing is yes, a strong argument, because you can recreate any moment and quickly understand the reasons for the bug. No side effects - when the function starts working with immutable objects, it stops changing the external code. The absence of leaks, in my opinion, is possible only when a functional approach is used, in which immutability is a fundamental principle.

  • Good example, thanks. - Ilya Bizunov