The Symbol in Javascript

Get to Know Symbols: The Unique Data Type for Object Properties

In JavaScript, symbols are unique data types that can be used to create identifiers for object properties. Symbols are not like strings or numbers, and they cannot be converted to those data types. This is what makes them ideal for creating identifiers.

Usage of Symbols in Javascript

When you create a symbol, you can optionally give it a description. This is useful for debugging, but it is not required.

Creating a symbol is simple.

const mySymbol = Symbol();

You can also create a symbol with a description.

const mySymbol = Symbol("my description");

If you create multiple symbols with the same description, they will be different values.

const sym1 = Symbol("foo");
const sym2 = Symbol("foo");

// false
console.log(sym1 === sym2);

What makes Symbols unique

Symbols are often used as identifiers for object properties. This is because symbols are guaranteed to be unique, and they are not converted to strings.

const obj = {};
obj[mySymbol] = "bar";

// "bar"

You can use symbols as keys for object properties, but you cannot use them as property names (keys) in JSON.

const sym = Symbol("foo");
const obj = { [sym]: "bar" };

// {}

Symbols are not enumerable, so they will not show up when you use a for-in loop on an object.

const obj = {};
obj[Symbol("a")] = "a";
obj[Symbol("b")] = "b";

for (var key in obj) {
  // undefined

You can use Object.getOwnPropertySymbols to get an array of all symbols on an object.

const obj = {};
obj[Symbol("a")] = "a";
obj[Symbol("b")] = "b";

const symbols = Object.getOwnPropertySymbols(obj);

// [Symbol(a), Symbol(b)]

Using a Symbol as an iterator

You can use the well-known Symbol.iterator to get a symbol that can be used as an iterator.

const arr = [1, 2, 3];
const it = arr[Symbol.iterator]();

// { value: 1, done: false }

// { value: 2, done: false }

// { value: 3, done: false }

// { value: undefined, done: true }

A more real-world example

You can create your own symbols, but there is no way to guarantee that they are unique. If you need a unique symbol, you should use Symbol().

Suppose you have an object that represents a person. You want to add a property to this object that stores the person's birth year, but you don't want this property to be enumerable. You can do this with a symbol:

const person = {
  name: "John Doe"
const birthYear = Symbol("birth year");
person[birthYear] = "1955";

for (var key in person) {
  // name

// 1955