- Published on
Immutable in Javascrip
- Authors
- Name
- Khánh
Introduction
An immutable value is a variable's value that cannot be changed without creating an entirely new value.
Primitive values are immutable - once created, their value cannot be changed, although the variable itself can be assigned a different value. On the other hand, by default, objects and arrays are mutable - their values and properties can be changed even when assigned through another variable.
The benefits of using immutable objects include:
- Improved performance (especially when there are no plans for future changes)
- Reduced memory usage (creating reference objects instead of cloning entire structures)
- Thread-safety (multiple threads can share an object without modifying it)
- Lower developer mental burden (object state remains unchanged, ensuring consistent behavior)
Use Object.freeze() to make an object immutable.
The different of Object.freeze vs Object.seal
Object.seal() fixes object properties but allows changing their values.
Object.freeze() makes an object immutable and prevents any changes.