Intermediate JavaScript Interview QuestionsIntermediateComparison
JavaScript · Question 60
What is the difference between Object.freeze(), Object.seal(), and Object.preventExtensions()?
Direct answer
preventExtensions blocks new own properties, seal additionally makes existing properties non-configurable, and freeze additionally makes existing data properties non-writable; all three are shallow operations.
Object.preventExtensions(obj)— no new own properties can be added, but existing configurable/writable properties can still be changed or removed according to their descriptors.Object.seal(obj)— prevents extensions and makes existing own properties non-configurable, so they cannot normally be deleted or reconfigured; writable data properties can still change value.Object.freeze(obj)— seals the object and makes existing data properties non-writable, providing the strongest of these three shallow restrictions.
“Shallow” matters: Object.freeze({settings:{theme:"dark"}}) does not automatically freeze the nested settings object. A deep-freeze utility must traverse the graph and handle cycles deliberately.
Freezing also does not mean all observable state reachable from the object can never change; accessor functions or referenced objects can still encapsulate mutable state.