What To Watch Out For In JavaScript Symbols

JavaScript

16/09/2021


In a previous article, I covered the basics of JavaScript Symbols. However, before using them, there are a few caveats you should be aware ⚠️ of.

Not always unique

As it turns out, Symbols aren't always unique, at least if you're using Symbol.for. If you create one using this method, a key 🔑 is required which acts as an identifier.

JAVASCRIPT
Symbol.for('key') === Symbol.for('key') // true

This means that any Symbols with the same key represent the same Symbol.

Keys are hidden

Symbols used as keys in an object are hidden 🙈 from methods such as

  • Object.keys, and
  • Object.getOwnPropertyNames()

as well as iterators like:

  • for...in, and
  • for...of
JAVASCRIPT
const fruits = {
[Symbol('banana')]: 2,
apple: 4,
}
Object.keys(fruits) // Array [ "apple" ]
for (const fruit in fruits) {
console.log(fruit) // apple
}

To actually ☝️ retrieve all the Symbols of an object, use the getOwnPropertySymbols instead.

JAVASCRIPT
Object.getOwnPropertySymbols(fruits) // Array [ Symbol("banana") ]

Convert to string

Symbols can't be implicitly coerced to a string as this will throw a type error. You first need to convert it to a string with the toString method.

JAVASCRIPT
Symbol('') + '' // TypeError: can't convert symbol to string
Symbol('').toString() + '' // "Symbol()"

WRITTEN BY

Code and stuff