ES10 - Symbol.Description

This tutorial covers Symbol Descriptions introduced ES2019 with examples..

Symbol descriptions accessor

Symbol is one of datatype in javascript. toString() method outputs string form of Symbol object.

console.log(Symbol('desc').toString());//outputs Symbol(desc)

There is no way to get description of Symbol object before ES10. One way is to parse the string representation, other way is using ES10 Symbol description

with Es10, new optional and read-only property description added to Symbol object, new accessor added by providing string as a description.

We can provide description during creation of symbol object for debugging the codes ] There are many ways we can create a symbol description

  • Using Symbol constructor
  • Symbol.for() method

Using Symbol constructor

Symbol object construction has optional description, once created, which can be retrieved using description parameter Syntax

const symbol=new Symbol(optionalDescription)

parameters are optional description used for debugging the object

Here is an example creating and usage of description

const desc="Symbol description example"
const symbol = Symbol(desc);
console.log(symbol);  //Symbol(Symbol description example)
console.log(symbol.description); //Symbol description example
console.log(symbol.toString()); //Symbol(Symbol description example)

Symbol.for().description method

Symbol.for(optionalDescription) finds the symbol for a given key in global registry, if founds returns the symbol, else create a new symbol

// print global symbol description
Symbol.for('global desc').toString();  // "Symbol(global desc)"
Symbol.for('global desc').description; // "global desc"