JavaScript Course
JavaScript
/
Intermediate

Object.freeze vs seal

Definition

Methods to lock down JavaScript objects. `freeze` makes an object completely immutable. `seal` prevents adding or deleting properties, but allows modifying existing ones.

Explain Like I'm New

`Object.freeze()` is putting the object in a block of ice. You can look at it, but you can't touch anything. `Object.seal()` is putting it in a tupperware container. You can't put new food in or take food out, but you can stir the food that is already inside.

Real World Example

Freezing a configuration object or Enum (`const COLORS = Object.freeze({ RED: '#F00' })`) so that other developers cannot accidentally alter global constants.

Common Use Cases

  • •State immutability
  • •Creating Enums in JavaScript

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What happens if you try to mutate a frozen object?

intermediate

  • Does `Object.freeze()` freeze nested objects?

advanced

  • What does `Object.preventExtensions()` do compared to `seal`?

Flash Cards

Question

Does it freeze nested objects?

Click to reveal answer
Answer

No! `Object.freeze()` is Shallow. If you have an object inside a frozen object, the inner object can still be mutated. You must write a recursive 'Deep Freeze' function to lock the entire tree.

Question

What is preventExtensions?

Click to reveal answer
Answer

`preventExtensions` is the weakest lock. You cannot add new properties, but you CAN modify existing ones AND you CAN delete existing ones. `seal` takes it a step further by preventing deletion.