JavaScript: Introduction to Symbols!

Abdul Kadir
Beginner's Guide to Mobile Web Development
3 min readApr 14, 2018

If you are a JavaScript developer you must already be aware of all the exciting new features that have been added in the ES6 specification. One of the lesser-known addition, but powerful is the — Symbol.

So what exactly is a Symbol?

The official Mozilla Developer Docs describe Symbol as:

“ The data type symbol is a primitive data type having the quality that, values of this type can be used to make object properties that are anonymous. This data type is used as the key for an object property when the property is intended to be private, for the internal use of a class or an object type”

The above definition is a little cryptic and might not be very intuitive at first glance. Here’s a simpler explanation that is a little easier to digest:

A symbol is a unique and immutable data type that is often used to identify object properties. Symbols have now been added to the list of primitives like — Number, boolean, String et al.

Here’s a situation where Symbols can be useful. For example, you are creating an object ‘fruit’ that looks something like this —

const fruit = {
'apple’: { color: 'red’, weight: 136.078 },
'banana’: { color: 'yellow’, weight: 183.15 },
'orange’: { color: 'orange’, weight: 170.097 }
};

Now suppose you want to add another property named ‘banana’. See the problem? You could do something like banana1, banana2, and so on..But that is not very elegant. This problem is solved by symbols. You can define two symbols like this —

const sym2 = Symbol('banana');
const sym3 = Symbol('banana');
console.log(sym2 === sym3);

Notice that both symbols have the same description but the output of the console statement returns false! The string is optional and is not used to access the symbol itself.

Syntax

The syntax for creating a symbol is pretty straightforward. We use the Symbol() function and pass an optional description String as an argument.

const sym1 = Symbol('foo');
console.log(sym1);

This creates a symbol sym1 of the type Symbol. Remember, the Symbol() function is not a constructor and the following syntax with the new keyword will produce an Error:

const sym = new Symbol(); //TypeError

Here are a few things you must keep in mind about Symbols:

  1. All symbols are unique! when you use Symbols in your objects you can rest assured that they will never clash with your String keys.
  2. Symbols cannot be read using existing methods like Object.getOwnPropertyNames(), Object.keys(). To read the symbols within your object ES6 now provides a special method Object.getOwnPropertySymbols()
  3. Symbols are not enumerable, that is, they do not appear in a for..in or a for..of loop
  4. Symbols may not always be unique. There’s a method Symbol.for() that returns a Symbol which isn’t unique. When in doubt, always create your own symbols!
  5. Symbols cannot be typecasted to primitive datatypes. Try something like this and it would throw an error,
console.log(' '+Symbol()); //Error
console.log(Symbol() + 'foo'); //Error

This is to prevent ‘stringifying’ of the symbol.

Some Well-Known Symbols!

These symbols are a bunch of static properties on the Symbol class and are implemented within Objects types like Arrays, Strings, etc; They represent internal language behaviour which was not accessible to developers previously in ES5.

Symbol.iterator

It’s a method that returns the default iterator for an object. It is used extensively with the new for..of loop. Here’s an example —

let arr = [1,2,3];

// with `for of`
for(let value of arr) {
console.log(value);
}

// without `for of`
let _arr = arr[Symbol.iterator]();
while(let _iteration = _arr.next()) {
if (_iteration.done) {
break;
}
let value = _iteration.value;
console.log(value);
}

Symbol.hasInstance

A method that determines whether an object is an instance, by the constructor object. It used to drive the behaviour of the instanceof operator.

Some other popular built-in symbols are — Symbol.match, Symbol.replace, Symbol.search, Symbol.split, Symbol.isConcatSpreadable etc. The workings of all these is beyond the scope of this post. However, if you are interested please head over to the MDN docs to try and understand them better.

I hope you guys learned a little something about Symbols and the advantages that they offer. As always, happy coding!

--

--

Abdul Kadir
Beginner's Guide to Mobile Web Development

SDE@ AWS Security. Interests include Android Development, System Design, and general Software Development Best practices