Choosing a Fixed Key Set

Freezing the shop’s settings locked their own values, which suits a record nobody should touch. A proof’s copy count is different. The customer asks for 20 copies, then changes their mind and asks for 25, so the value has to stay editable. What shouldn’t change is the shape of the record. A stray extra key, or a typo such as copeis, would slip into the export without anyone noticing.

Freezing is too strong for that record, and leaving it open is too weak. In this lesson, you’ll lock the key set while keeping the values editable, and you’ll compare the three locking levels JavaScript offers by the property flags each one sets.

Fix the Keys With Object.seal()

In Python, the closest tool is @dataclass(slots=True). Slots exist mainly to save memory, but as a side effect an instance of a slotted class like this one, with no __dict__ inherited from a base class, can hold only the declared names. So assigning to a declared field works and assigning to any other name fails:

Language: Python
from dataclasses import dataclass

@dataclass(slots=True)
class ProofCount:
    copies: int

count = ProofCount(20)
count.copies = 25
count.extra = 1  # Raises AttributeError

JavaScript has no class-level list of allowed names for a plain object. Instead, you lock the object itself after you build it. Object.seal() takes an object, stops it from gaining or losing properties, and returns the same object, much as Object.freeze() does.

The examples here run as ES modules, which use strict mode, so a refused write throws a TypeError instead of failing silently. As a reminder, const declares a name that can’t be reassigned, try runs a block, and catch receives the error if the block throws. err.name holds the error’s type, and console.log() prints a value:

Language: JavaScript
const sealed = Object.seal({ copies: 20 });
sealed.copies = 25;
console.log(sealed.copies);
try {
  sealed.extra = 1;
} catch (err) {
  console.log(err.name);
}

The change to the existing key goes through, while the new key is refused:

Language: Program Output
25
TypeError

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.