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

JS Symbols

A Symbol is a one-of-a-kind label that is never equal to any other, like a unique fingerprint. It is used for property names that must not clash.
Syntax
javascript
const symbolName = Symbol("description");
const object = { [symbolName]: value };

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.

उदाहरण: 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.

उदाहरण: 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.

उदाहरण: Symbol Descriptions

javascript
// Declare the constant `s`, set to `Symbol("debug label")`
// Declare the constant `s`, set to `Symbol("debug label")`
const s = Symbol("debug label");
// Print `s.toString()` to the console
// Print `s.toString()` to the console
console.log(s.toString());
// Print `s.description` to the console
// Print `s.description` to the console
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().

उदाहरण: 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.

उदाहरण: Well-Known Symbols

javascript
const arr = [1, 2, 3];
console.log(typeof arr[Symbol.iterator]); // "function", built-in well-known symbol
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

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.