JavaScript TutorialDatatypes in JavaScriptEvaluating JavaScriptFunctional JavaScriptJavaScript .postMessage() and MessageEventJavaScript AJAXJavaScript Anti-patternsJavaScript Arithmetic (Math)JavaScript ArraysJavaScript Arrow FunctionsJavaScript Async functions (async/await)JavaScript Async IteratorsJavaScript Automatic Semicolon Insertion - ASIJavaScript Battery Status APIJavaScript Behavioral Design PatternsJavaScript Binary DataJavaScript Bitwise operatorsJavaScript Bitwise Operators - Real World Examples (snippets)JavaScript BOM (Browser Object Model)JavaScript Built-in ConstantsJavaScript CallbacksJavaScript ClassesJavaScript CommentsJavaScript Comparison OperationsJavaScript ConditionsJavaScript ConsoleJavaScript Constructor functionsJavaScript Context (this)JavaScript CookiesJavaScript Creational Design PatternsJavaScript Custom ElementsJavaScript Data attributesJavaScript Data ManipulationJavaScript DateJavaScript Date ComparisonJavaScript DebuggingJavaScript Declarations and AssignmentsJavaScript Destructuring assignmentJavaScript Detecting browserJavaScript EnumerationsJavaScript Error HandlingJavaScript Escape SequencesJavaScript EventsJavaScript execCommand and contenteditableJavaScript FetchJavaScript File API, Blobs and FileReadersJavaScript Fluent APIJavaScript FunctionsJavaScript GeneratorsJavaScript GeolocationJavaScript Global error handling in browsersJavaScript HistoryJavaScript How to make iterator usable inside async callback functionJavaScript IndexedDBJavaScript InheritanceJavaScript Intervals and TimeoutsJavaScript JSONJavaScript Linters - Ensuring code qualityJavaScript LocalizationJavaScript LoopsJavaScript MapJavaScript Memory efficiencyJavaScript Method ChainingJavaScript Modals - PromptsJavaScript Modularization TechniquesJavaScript ModulesJavaScript NamespacingJavaScript Navigator ObjectJavaScript Notifications APIJavaScript ObjectsJavaScript Performance TipsJavaScript PromisesJavaScript Prototypes, objectsJavaScript ProxyJavaScript Regular expressionsJavaScript requestAnimationFrameJavaScript Reserved KeywordsJavaScript Same Origin Policy & Cross-Origin CommunicationJavaScript ScopeJavaScript ScreenJavaScript Security issuesJavaScript Selection APIJavaScript Server-sent eventsJavaScript SetJavaScript Setters and GettersJavaScript Strict modeJavaScript StringsJavaScript SymbolsJavaScript Tail Call OptimizationJavaScript Template Literals

JavaScript Symbols

From WikiOD

Syntax[edit | edit source]

  • Symbol()
  • Symbol(description)
  • Symbol.toString()

Remarks[edit | edit source]

ECMAScript 2015 Specification 19.4 Symbols

Basics of symbol primitive type[edit | edit source]

Symbol is a new primitive type in ES6. Symbols are used mainly as property keys, and one of its main characteristics is that they are unique, even if they have the same description. This means they will never have a name clash with any other property key that is a symbol or string.

const MY_PROP_KEY = Symbol();
const obj = {};

obj[MY_PROP_KEY] = "ABC";

In this example, the result of console.log would be ABC.

You can also have named Symbols like:

const APPLE    = Symbol('Apple');
const BANANA   = Symbol('Banana');
const GRAPE    = Symbol('Grape');

Each of these values are unique and cannot be overridden.

Providing an optional parameter (description) when creating primitive symbols can be used for debugging but not to access the symbol itself (but see the Symbol.for() example for a way to register/lookup global shared symbols).

Using Symbol.for() to create global, shared symbols[edit | edit source]

The Symbol.for method allows you to register and look up global symbols by name. The first time it is called with a given key, it creates a new symbol and adds it to the registry.

let a = Symbol.for('A');

The next time you call Symbol.for('A'), the same symbol will be returned instead of a new one (in contrast to Symbol('A') which would create a new, unique symbol that happens to have the same description).

a === Symbol.for('A') // true


a === Symbol('A') // false

Converting a symbol into a string[edit | edit source]

Unlike most other JavaScript objects, symbols are not automatically converted into a string when performing concatenation.

let apple = Symbol('Apple') + ''; // throws TypeError!

Instead, they have to be explicitly converted into a string when necessary, (for example, to get a textual description of the symbol that can be used in a debug message) using the toString method or the String constructor.

const APPLE = Symbol('Apple');
let str1 = APPLE.toString(); // "Symbol(Apple)"
let str2 = String(APPLE);    // "Symbol(Apple)"