Party tricks with ES6 symbols

Yoshua Wuyts
2 min readApr 30, 2015

--

Symbols are a new primitive in ES6. A symbol in itself isn’t very interesting, as it doesn’t really do anything. They mostly become interesting when using them as keys to Objects. Here’s some symbol basics:

Function identifying with symbols

Checking if functions / objects are equal in JS is typically done with the === operator. This checks if both functions point to the same location in memory, and then returns a Boolean. In cases where you want to check if a function or object is of a certain type (e.g. generated by a factory), you’re going to have a hard time.

What you would want to do is attach a flag to the object to mark it as being a certain type. Luckily with ES6 you can attach unique, non-enumerable flags (which means they don’t show up when iterating over the keys) by using ES6 symbols.

Here’s an example:

Private properties with symbols

Another neat usage for symbols is private properties in objects & classes. Traditionally this has been done by prefixing properties with an underscore (e.g. this._property) or by wrapping variables in closures. Symbols allow true private properties in OOP. Combined with setters and getters they allow for powerful interactions. Here’s an example:

Do keep in mind, however, that with by using Object.getOwnProperties() all symbols can be retrieved from an object, thus anonimity isn’t guaranteed.

Wrapping up

If you want to use ES6 symbols today, check out es6-symbol. Alternatively you can use babel for non-module code.

And that’s it! I hope you were able to pick up some new party tricks to impress friends at parties, cat cafes or on IRC.

Edit: thanks to Frankie Bagnardi for contributing several improvements.

Originally published at github.com on April 29, 2015.

--

--