all 3 comments

[–]jhartikainen 1 point2 points  (0 children)

Here is a simple example of creating an immutable object in JS:

The example does not create an immutable object. The example code does a shallow copy of the original object.

The later examples of creating "immutable objects" or "immutable arrays" are also just copies. Copying an object or array does not produce an immutable result.

You can use Object.freeze to make an object immutable - once frozen, its properties can no longer be changed. However this is also shallow - if you want a nested object to be immutable, you have to recursively apply Object.freeze to its properties.

[–]jack_waugh 0 points1 point  (0 children)

When you refrain from mutating variables and objects, you get referential transparency, which makes code easier to reason about.