Symbols in ECMAScript 6

I learned today that ECMAScript 6 will support a new primitive type called a symbol. This is inspired by symbols from Ruby which I wrote about in this post.

For those of you who may not know or didn’t read the aforementioned link, a symbol is really just a way of uniquely identifying a property, etc. For example, let’s say we wanted to represent the cardinal directions. Now, you could just have an object with properties like so:

[sourcecode language=”javascript”]

var directions = {

north: “NORTH”,

south: “SOUTH”,

east: “EAST”,

west: “WEST”



Obviously a trite and somewhat inaccurate example, but bare with me. So the problem with this is that we don’t really care what the value of any direction would be. We just need a way to represent the directions in a unique way. This is where using symbols for the directions would be handy.

Here’s what that would look like:

[sourcecode language=”javascript”]

var NORTH = Symbol(),

SOUTH = Symbol(),

EAST = Symbol(),

WEST = Symbol();


Now we could just do something like:

[sourcecode language=”javascript”]

switch(direction) {

case: NORTH





Symbols are a better way of handling situations like this since strings may not be unique and generally speaking, doing any kind of check on a string’s value is an antipattern and not recommended.

Don Marges

Don Marges

Pragmatic Software Developer

comments powered by Disqus
rss facebook twitter github youtube mail spotify instagram linkedin