CodeBlanks Logo Icon CodeBlanks

Symbol

Learn unique identifiers with Symbol.

Symbol

A Symbol is a unique and immutable primitive type in JavaScript. Each call to Symbol() creates a new, unique value.

Example: const a = Symbol('id') and const b = Symbol('id'). Even though the descriptions match, a === b returns false; they are two different symbols.

Symbols are usually used to add private keys to objects; other code cannot accidentally overwrite them.

Symbol uniqueness

Two Symbols are never equal to each other, even if their descriptions match. This makes them 'clash-free keys'.

Example: const a = Symbol('x'), const b = Symbol('x'). a === b returns false. The description is just a label for debugging; it does not affect uniqueness.

If you really want to share the 'same' Symbol, you can use Symbol.for('key'); this looks up a global registry. But this is an advanced topic.

Practice Compare two Symbols

Define two separate Symbols: const a = Symbol('id') and const b = Symbol('id'). Check equality with console.log(a === b); also print its type with console.log(typeof a).

Starter code

index.js
// Define two separate Symbols (with the same description)
// Log a === b and typeof a

Sample solution

index.js
const a = Symbol("id");
const b = Symbol("id");
console.log(a === b);
console.log(typeof a);

Expected output

false
symbol

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is Symbol used for?

  • For unique keys Correct answer
  • To create arrays
  • To concatenate strings
  • To round numbers

Explanation: Symbol creates unique keys.

2 Match the Symbol properties

Term Meaning
Symbol() Unique value
Symbol('id') Symbol with description
typeof s 'symbol'
s === s Only equal to itself

3 Define a Symbol

Question
const id = ____;
Answer
const id = Symbol('id');

Explanation: Symbol('id') creates a new unique symbol.

All lessons in Beginner