Difference between freeze and seal
I wrote a test project which compares these 3 methods:
Object.freeze()
Object.seal()
Object.preventExtensions()
My unit tests cover CRUD cases:
- [C] add new property
- [R] read existed property
- [U] modify existed property
- [D] remove existed property
Result:
Object.seal
- It prevents adding and/or removing properties from the sealed object; using
delete
will return false - It makes every existing property non-configurable: they cannot be converted from 'data descriptors' to 'accessor descriptors' (and vice versa), and no attribute of accessor descriptors can be modified at all (whereas data descriptors can change their
writable
attribute, and theirvalue
attribute ifwriteable
is true). - Can throw a
TypeError
when attempting to modify the value of the sealed object itself (most commonly in strict mode)
Object.freeze
- Exactly what
Object.seal
does, plus: - It prevents modifying any existing properties
Neither one affects 'deep'/grandchildren objects. E.g., if obj
is frozen, obj.el
can’t be reassigned, but the value of obj.el
could be modified, e.g. obj.el.id
can be changed.
Performance:
Sealing or freezing an object may affect its enumeration speed, depending on the browser:
- Firefox: enumeration performance is not impacted
- IE: enumeration performance impact is negligible
- Chrome: enumeration performance is faster with sealed or frozen objects
- Safari: sealed or frozen objects enumerate 92% slower (as of 2014)
Tests: Sealed objects, Frozen objects.
You can always looks these up in MDN. In short:
- Freeze: makes the object immutable, meaning no change to defined property allowed, unless they are objects.
- Seal: prevent addition of properties, however defined properties still can be changed.