JavaScript Symbols Basics of symbol primitive type


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).