Javascript - Data Types Symbol

Introduction

ES6 introduces a brand new primitive data type - Symbol.

Symbols represent a unique value.

A symbol is a unique token that is guaranteed to never clash with any other Symbol.

Symbols in ES6 can be created using a factory function.

The Symbol() method can be used to create a new symbol.

const foo = Symbol(); 
console.log(typeof foo);      // "symbol" 

Every time you call the factory function, a new and unique symbol is created.

The from the typeof on a symbol type is "symbol," and this is the primary way to identify symbols:

Symbols in ES6 do not have a literal form like other primitives.

Optionally, you can create a Symbol out of a string:

const chocolate = Symbol("Jack"); 
console.log(chocolate); // Symbol(Jack) 
console.log(chocolate.toString()); // "Symbol(Jack)" 

The label passed in does not affect the value of the Symbol.

It is only used to describe the symbol while printing it.

You should not be using the new keyword for creating symbols.

Symbols do not have an object constructor; therefore you cannot create a Symbol using the new keyword:

const bar = new Symbol();           // Type Error 

A symbol is always unique and two symbols can never be the same.

You can create multiple symbols with the same label but the returned symbols would always be unique.

const kit = Symbol("hello"); 
const kat = Symbol("hello"); 
console.log(kit === kat);       // false 

or you can simply try,

Symbol() !== Symbol()         // true 

Related Topics