Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 14.5 — Symbols and Well-Known Symbols
JavaScript · Example 3 of 3 ES2015+

Symbols as constants that can't be faked

Mallory's symbol has the same description as Status.ACTIVE, but it's a different symbol, so it doesn't match. String(u.status) converts on purpose; + would throw.

A symbol is a unique, primitive value used as a property key that can never clash with another key; the language's own well-known symbols, such as Symbol.iterator and Symbol.toPrimitive, are hooks that let your objects change how built-in operations treat them.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Create a Temperature class whose instances give their Celsius number for +t and "21°C" in a template literal. Log both for new Temperature(21).

02

Add a hidden createdBy tag to an object with a symbol key, then show that JSON.stringify doesn't include it but direct access does.

Explain it without notes

01

What is a symbol and what problem does it solve?

02

What is the difference between Symbol("x") and Symbol.for("x")?

03

Which operations see symbol-keyed properties and which skip them?

04

What is Symbol.toPrimitive, and what are its three hints?

Symbols as constants that can't be faked ES2015+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Asha can log in Symbol(active)
Ravi cannot log in Symbol(blocked)
Mallory unknown status Symbol(active)