← Back to JavaScript Course | Chapter 5: ES6+ Features | Lesson 9 of 12

JS Symbols

Creating Symbols

Symbol() creates a new, completely unique value every time it's called, even if you pass the same description string — no two symbols are ever equal to each other.

Example: Creating Symbols

javascript
const s1 = Symbol("id");
const s2 = Symbol("id");
console.log(s1 === s2); // false, always unique

Symbol Properties

A symbol can be used as an object property key, and properties keyed by a symbol are hidden from normal enumeration (for...in, Object.keys), making them useful for semi-private metadata.

Example: Symbol Properties

javascript
const id = Symbol("id");
const user = { name: "Sam", [id]: 123 };
console.log(Object.keys(user)); // ["name"], symbol hidden

Symbol Descriptions

The optional string passed to Symbol(description) is purely for debugging/display purposes (shown in console output or .toString()) and has no effect on the symbol's uniqueness or identity.

Example: Symbol Descriptions

javascript
const s = Symbol("debug label");
console.log(s.toString());
console.log(s.description);

Global Symbol Registry

Symbol.for(key) looks up (or creates) a symbol in a global registry shared across your whole program, so calling it twice with the same key returns the exact same symbol — unlike Symbol().

Example: Global Symbol Registry

javascript
const a = Symbol.for("shared");
const b = Symbol.for("shared");
console.log(a === b); // true, same registry key

Well-Known Symbols

JavaScript defines built-in well-known symbols like Symbol.iterator, which objects use to opt into being iterable with for...of — a core mechanism the language itself relies on.

Example: Well-Known Symbols

javascript
const arr = [1, 2, 3];
console.log(typeof arr[Symbol.iterator]); // "function", built-in well-known symbol

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.