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 ...