Skip to the content

Frozen objects

JavaScript · Unit 15: Immutability

All of this depends on nobody forgetting to copy. Object.freeze(obj) puts the lock on: the object becomes read-only.

In the mode your code runs in, assigning to a frozen property crashes with TypeError.

const menu = Object.freeze({
  dish: "soup",
});
try {
  menu.dish = "stew";
} catch (e) {
  console.log(e.name);
}
console.log(menu.dish);

Prints

TypeError
soup

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    The config is frozen and someone tries to add a property. What does it print?

  2. 2. Multiple choice

    How are const and Object.freeze different?

  3. 3. Predict the output

    An array gets frozen and then a push. What does it print?

  4. 4. Complete the code

    Fill in the blank so the config is protected and the 99 doesn't get in.

  5. 5. Predict the output

    The team is frozen, yet a player gets signed. What does it print?

  6. 6. Find the bug

    This program should print a fresh config with max at 50, without touching the frozen one. Which line has the error?

  7. 7. Put the lines in order

    Put the program in order: it tries to raise the max of a frozen config and, instead of crashing, prints the name of the error and the value that stayed.

  8. 8. Complete the code

    Fill in the blank so raise returns the max plus 5, without touching the frozen config.

  9. 9. Find the case that fails

    adjust(conf, n) returns a fresh config with max at n, without changing the one it receives; to make sure, it freezes it on the way in. Which call does it fail on?

  10. 10. Predict the output

    Two ways of sorting the same frozen array. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →