Creating Symbols
Symbols are unique among JavaScript primitives in that they don’t have a literal form, like true
for booleans or 42
for numbers. You can create a symbol by using the global Symbol
function, as in this example:
let firstName = Symbol();
let person = {};
person[firstName] = "Nicholas";
console.log(person[firstName]); // "Nicholas"
Here, the symbol firstName
is created and used to assign a new property on the person
object. That symbol must be used each time you want to access that same property. Naming the symbol variable appropriately is a good idea, so you can easily tell what the symbol represents.
W> Because symbols are primitive values, calling new Symbol()
throws an error when called. You can create an instance of Symbol
via new Object(yourSymbol)
as well, but it’s unclear when this capability would be useful.
The Symbol
function also accepts an optional argument that is the description of the symbol. The description itself cannot be used to access the property, but is used for debugging purposes. For example:
let firstName = Symbol("first name");
let person = {};
person[firstName] = "Nicholas";
console.log("first name" in person); // false
console.log(person[firstName]); // "Nicholas"
console.log(firstName); // "Symbol(first name)"
A symbol’s description is stored internally in the [[Description]]
property. This property is read whenever the symbol’s toString()
method is called either explicitly or implicitly. The firstName
symbol’s toString()
method is called implictly by console.log()
in this example, so the description gets printed to the log. It is not otherwise possible to access [[Description]]
directly from code. I recommended always providing a description to make both reading and debugging symbols easier.
A> ### Identifying Symbols A> A>Since symbols are primitive values, you can use the typeof
operator to determine if a variable contains a symbol. ECMAScript 6 extends typeof
to return "symbol"
when used on a symbol. For example: A> A>js A>let symbol = Symbol("test symbol"); A>console.log(typeof symbol); // "symbol" A>
A> A>While there are other indirect ways of determining whether a variable is a symbol, the typeof
operator is the most accurate and preferred technique.