Monday, January 25, 2016

Preparing for ECMAScript 6: Symbols and Their Uses

While ES2015 has introduced many language features that have been on developers' wish lists for some time, there are some new features that are less well known and understood, and the benefits of which are much less clear. One such feature is the symbol. The symbol is a new primitive type, a unique token that is guaranteed never to clash with another symbol. In this sense, you could think of them as a kind of UUID (Universally Unique Identifier). Let's look at how they work, and what we can do with them (Note: all examples in this article have been tested in the latest versions of Chrome and Firefox for Linux, but the behavior may vary from browser to browser or when using tools such as Firebug).

Creating New Symbols

[author_more]

Creating new symbols is very straightforward and is simply a case of calling the Symbol function. Note that this is a just a standard function and not an object constructor. Trying to call it with the new operator will result in a TypeError. Every time you call the Symbol function, you will get a new and completely unique value.

let foo = Symbol();
let bar = Symbol();

foo === bar
// <-- false

Symbols can also be created with a label, by passing a string as the first argument. The label does not affect the value of the symbol, but is useful for debugging, and is shown if the symbol's toString() method is called. It's possible to create multiple symbols with the same label, but there's no advantage to doing so and this would probably just lead to confusion.

let foo = Symbol('baz');
let bar = Symbol('baz');

foo === bar
// <-- false
console.log(foo);
// <-- Symbol(baz)

What Can I Do With Them?

Symbols could often be a good replacement for strings or integers as class/module constants:

class Application {
  constructor(mode) {
    switch (mode) {
      case Application.DEV:
        // Set up app for development environment
        break;
      case Application.PROD:
        // Set up app for production environment
        break;
      case default:
        throw new Error('Invalid application mode: ' + mode);
    }
  }
}

Application.DEV = Symbol('dev');
Application.PROD = Symbol('prod');

// Example use
let app = new Application(Application.DEV);

String and integers are not unique values; values such as the number 2 or the string 'development', for example, could also be in use elsewhere in the program for different purposes. Using symbols means we can be more confident about the value being supplied.

Another interesting use of symbols is as object property keys. If you've ever used a JavaScript object as a hashmap (an associative array in PHP terms, or dictionary in Python) you'll be familiar with getting/setting properties using the bracket notation:

let data = [];

data['name'] = 'Ted Mosby';
data['nickname'] = 'Teddy Westside';
data['city'] = 'New York';

Continue reading %Preparing for ECMAScript 6: Symbols and Their Uses%


by Nilson Jacques via SitePoint

No comments:

Post a Comment