Reliable and Recognized JavaScript Certification Online #

Symbols are new primitive type added in ECMAScript 2015. Symbols do not have a literal syntax, they have a Symbol() function that can be used to create them.
Symbol() function is rather a factory, it is not a constructor. The function takes one optional argument description.

var symbol = new Symbol('symbol'); // TypeError: Symbol is not a constructor 
// correct way:
var symbol = Symbol('mySymbol'); 
console.log(symbol); // Symbol(mySymbol)

Symbols are unique. Each new symbol has new, unique value.
If you create new symbols:

var mySymbol = Symbol();
var mySymbol2 = Symbol();

JavaScript engine creates a completely new values for them.
It means that:

Symbol() === Symbol() // false


The use of Symbols

Symbols may be used as unique property keys. They prevent name clashes.

var p1 = Symbol('p');
var p2 = Symbol('p');
var p3 = Symbol('p');
var object = {
    [p1]: 1,
    [p2]: 2,
object[p3] = 3; 

They may be used as constants representing concepts:

const CATEGORY_PHONES = Symbol('phones');
const CATEGORY_LAPTOPS = Symbol('laptops');
const CATEGORY_TV = Symbol('tv');
const CATEGORY_CONSOLES = Symbol('consoles');

No Comments