Using symbols as the object property keys

Until ES5, the JavaScript object property keys had to be string type. But since ES6, the JavaScript object property keys can be strings or symbols. Here is an example that demonstrates how to use a symbol as an object property key:

let obj = null;let s1 = null;(function(){ let s2 = Symbol(); s1 = s2; obj = {[s2]: "mySymbol"} console.log(obj[s2]); console.log(obj[s2] == obj[s1]);})();console.log(obj[s1]);

The output is:

mySymboltruemySymbol

From the preceding code, you can see that in order to create or retrieve a property key using symbols, you need to use the [] token. We saw the [] token while discussing the computed property names in Chapter 2, Knowing Your Library.

To access a symbol property ...

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.