JavaScript for impatient programmers (beta)
Please support this book: buy it or donate
(Ad, please don’t block.)

20 Symbols



Symbols are primitive values that are created via the factory function Symbol():

const mySymbol = Symbol('mySymbol');

The parameter is optional and provides a description, which is mainly useful for debugging.

On one hand, symbols are like objects in that each value created by Symbol() is unique and not compared by value:

> Symbol() === Symbol()
false

On the other hand, they also behave like primitive values. They have to be categorized via typeof:

const sym = Symbol();
assert.equal(typeof sym, 'symbol');

And they can be property keys in objects:

const obj = {
  [sym]: 123,
};

20.1 Use cases for symbols

The main use cases for symbols, are:

20.1.1 Symbols: values for constants

Let’s assume you want to create constants representing the colors red, orange, yellow, green, blue and violet. One simple way of doing so would be to use strings:

const COLOR_BLUE = 'Blue';

On the plus side, logging that constant produces helpful output. On the minus side, there is a risk of mistaking an unrelated value for a color, because two strings with the same content are considered equal:

const MOOD_BLUE = 'Blue';
assert.equal(COLOR_BLUE, MOOD_BLUE);

We can fix that problem via symbols:

const COLOR_BLUE = Symbol('Blue');
const MOOD_BLUE = Symbol('Blue');

assert.notEqual(COLOR_BLUE, MOOD_BLUE);

Let’s use symbol-valued constants to implement a function:

const COLOR_RED    = Symbol('Red');
const COLOR_ORANGE = Symbol('Orange');
const COLOR_YELLOW = Symbol('Yellow');
const COLOR_GREEN  = Symbol('Green');
const COLOR_BLUE   = Symbol('Blue');
const COLOR_VIOLET = Symbol('Violet');

function getComplement(color) {
  switch (color) {
    case COLOR_RED:
      return COLOR_GREEN;
    case COLOR_ORANGE:
      return COLOR_BLUE;
    case COLOR_YELLOW:
      return COLOR_VIOLET;
    case COLOR_GREEN:
      return COLOR_RED;
    case COLOR_BLUE:
      return COLOR_ORANGE;
    case COLOR_VIOLET:
      return COLOR_YELLOW;
    default:
      throw new Exception('Unknown color: '+color);
  }
}
assert.equal(getComplement(COLOR_YELLOW), COLOR_VIOLET);

20.1.2 Symbols: unique property keys

The keys of properties (fields) in objects are used at two levels:

The following code demonstrates the difference:

const pt = {
  x: 7,
  y: 4,
  toString() {
    return `(${this.x}, ${this.y})`;
  },
};
assert.equal(String(pt), '(7, 4)');

Properties .x and .y exist at the base level. They hold the coordinates of the point represented by pt and are used to solve a problem – computing with points. Method .toString() exists at a meta-level. It is used by JavaScript to convert this object to a string.

Meta-level properties must never interfere with base level properties. That is, their keys must never overlap. That is difficult when both language and libraries contribute to the meta-level. For example, it is now impossible to give new meta-level methods simple names, such as toString, because they might clash with existing base level names. Python’s solution to this problem is to prefix and suffix special names with two underscores: __init__, __iter__, __hash__, etc. However, even with this solution, libraries can’t have their own meta-level properties, because those might be in conflict with future language properties.

Symbols, used as property keys, help us here: Each symbol is unique and a symbol key never clashes with any other string or symbol key.

20.1.2.1 Example: a library with a meta-level method

As an example, let’s assume we are writing a library that treats objects differently if they implement a special method. This is what defining a property key for such a method and implementing it for an object would look like:

const specialMethod = Symbol('specialMethod');
const obj = {
  _id: 'kf12oi',
  [specialMethod]() { // (A)
    return this._id;
  }
};
assert.equal(obj[specialMethod](), 'kf12oi');

The square brackets in line A enable us to specify that the method must have the key specialMethod. More details are explained in §25.5.2 “Computed property keys”.

20.2 Publicly known symbols

Symbols that play special roles within ECMAScript are called publicly known symbols. Examples include:

  Exercises: Publicly known symbols

20.3 Converting symbols

What happens if we convert a symbol sym to another primitive type? Tbl. 14 has the answers.

Table 14: The results of converting symbols to other primitive types.
Convert to Explicit conversion Coercion (implicit conv.)
boolean Boolean(sym) OK !sym OK
number Number(sym) TypeError sym*2 TypeError
string String(sym) OK ''+sym TypeError
sym.toString() OK `${sym}` TypeError

One key pitfall with symbols is how often exceptions are thrown when converting them to something else. What is the thinking behind that? First, conversion to number never makes sense and should be warned about. Second, converting a symbol to a string is indeed useful for diagnostic output. But it also makes sense to warn about accidentally turning a symbol into a string (which is a different kind of property key):

const obj = {};
const sym = Symbol();
assert.throws(
  () => { obj['__'+sym+'__'] = true },
  { message: 'Cannot convert a Symbol value to a string' });

The downside is that the exceptions make working with symbols more complicated. You have to explicitly convert symbols when assembling strings via the plus operator:

> const mySymbol = Symbol('mySymbol');
> 'Symbol I used: ' + mySymbol
TypeError: Cannot convert a Symbol value to a string
> 'Symbol I used: ' + String(mySymbol)
'Symbol I used: Symbol(mySymbol)'

  Quiz

See quiz app.