Symbol Coercion

Type coercion is a significant part of JavaScript, and there’s a lot of flexibility in the language’s ability to coerce one data type into another. Symbols, however, are quite inflexible when it comes to coercion because other types lack a logical equivalent to a symbol. Specifically, symbols cannot be coerced into strings or numbers so that they cannot accidentally be used as properties that would otherwise be expected to behave as symbols.

The examples in this chapter have used console.log() to indicate the output for symbols, and that works because console.log() calls String() on symbols to create useful output. You can use String() directly to get the same result. For instance:

  1. let uid = Symbol.for("uid"),
  2. desc = String(uid);
  3. console.log(desc); // "Symbol(uid)"

The String() function calls uid.toString() and the symbol’s string description is returned. If you try to concatenate the symbol directly with a string, however, an error will be thrown:

  1. let uid = Symbol.for("uid"),
  2. desc = uid + ""; // error!

Concatenating uid with an empty string requires that uid first be coerced into a string. An error is thrown when the coercion is detected, preventing its use in this manner.

Similarly, you cannot coerce a symbol to a number. All mathematical operators cause an error when applied to a symbol. For example:

  1. let uid = Symbol.for("uid"),
  2. sum = uid / 1; // error!

This example attempts to divide the symbol by 1, which causes an error. Errors are thrown regardless of the mathematical operator used (logical operators do not throw an error because all symbols are considered equivalent to true, just like any other non-empty value in JavaScript).