Command Palette

Search for a command to run...

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

Symbols as unique, hidden-from-JSON keys

description is ES2019. The symbol key is skipped by Object.keys and JSON, but anyone can still list it with getOwnPropertySymbols.

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 unique, hidden-from-JSON keys ES2015+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

symbol
false
Symbol(id) id
42
[ 'name' ]
{"name":"Asha"}
[ Symbol(id) ]
[ 'name', Symbol(id) ]
true
app.id
undefined