2 ms·
> But can I then add and remove items from an immutable object to create new objects? Yes, although the new object is not frozen by default. Adding is quite st
by mrighele 7y ago
> But can I then add and remove items from an immutable object to create new objects?
Yes, although the new object is not frozen by default.
Adding is quite straight forward, expecially with the spread syntax
let x = { a: 1, b: 2 };
Object.freeze(x)
let y = {...x, b: 3}
// y == { a: 1, b: 3 }
Removing is less intuitive
let x = { a: 1, b: 2 };
Object.freeze(x)
let { b, ...y} = x;
// y == { a: 1 }
> And the 'frozenness' isn't communicated through the language
Yes, but given that JS is a dynamic language I wouldn't expect anything different (everything must inspected at runtime).
> And freeze isn't recursive against the entire object graph
You're right, although one could quickly implement a recursive version.
In any case I find Object.freeze not much useful since trying to mutate a frozen object will simply ignore the operation; I think that most of the time trying to do that should be considered an error and I would prefer to have and exception raised.