javascript · level 3 · unit 4 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
const locks the label, not the box. Freezing locks the box.
const settings = { } stops you pointing settings at a new object, but anyone can still it: settings.theme = "dark" works. When two parts of a program share that object, one quiet change surprises the other.
makes it : in strict mode, changing, adding or deleting a property throws a TypeError. Beware: freezing is . Objects nested inside stay changeable unless you freeze them too.
const settings = Object.freeze({ theme: "light", sizes: [12, 14] });
try {
settings.theme = "dark";
} catch (error) {
console.log(`${error.name}: settings are frozen`);
}
settings.sizes.push(99);
console.log(settings.theme, settings.sizes, Object.isFrozen(settings.sizes)); Object.isFrozen(x) tells you whether x itself is frozen.
guess first
Two names, one array. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const team = ["Ava", "Ben"];
const squad = team;
squad.push("Cal");
const frozen = Object.freeze(["Dee"]);
console.log(team.length, squad === team);
console.log(Object.isFrozen(team), Object.isFrozen(frozen));
your turn
Your turn. Freeze the price list.
Fill in the function that freezes the prices, then pick an item to try raising. Strict mode should block the change.
fix it
A frozen user moved house. Can you fix it?
useris frozen, so why could the city change?- Freezing is shallow. The
addressobject nested inside is not frozen. - Wrap the address in its own freeze:
address: Object.freeze({ city: "Leeds" }).
nailed it
your data stays put now. :D
conststops reassigning a name, not mutating the object.Object.freezemakes an object's own properties read-only.- Freezing is shallow, so freeze nested objects too.
new words in your collection
- mutate
- immutable
- Object.freeze
- shallow
This lesson isn’t saved. A free account remembers every lesson you finish.