Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Symbol

Creates a unique value — for example, a key that never clashes with others.

Available since: ES2015

Syntax

Symbol(description)

Parameters

ParameterTypeDescription
descriptionstringOptional. A description for debugging.

Return value

symbolA new unique value.

Examples

Every symbol is unique:

const a = Symbol('id');
const b = Symbol('id');
 
console.log(a === b);
console.log(typeof a, a.description);

Output:

false
symbol id

A symbol as a hidden object key:

const id = Symbol('id');
const user = { name: 'Anna', [id]: 42 };
 
console.log(user[id]);
console.log(Object.keys(user));
console.log(JSON.stringify(user));

Output:

42
[
  "name"
]
{"name":"Anna"}

Notes

Symbol-keyed properties are skipped by Object.keys(), for...in and JSON.stringify(). Symbol is called without new.

See also

  • Symbol.for — Returns a shared symbol by name: the same name gives the same symbol.
  • Symbol.iterator — A special key that makes an object iterable in for...of and spread.
  • typeof — Returns a string with the type of a value.

In the tutorial

  • Symbols — The symbol type in JavaScript: unique values, symbols as object keys, hidden properties, the Symbol.for global registry and built-in symbols.

Thanks for reading!

Donate to the site — we work hard for you.