DEV Community

Cover image for JavaScript(ES6) Symbols
Puja Kundu
Puja Kundu

Posted on

JavaScript(ES6) Symbols

What is symbol in JavaScript?

Symbol is a primitive data type that is unique and immutable. Every symbol has a hidden unique value. It is usually used to avoid name conflicts between object properties, and keys.

Syntax

Unlike other primitve data types, we can not create symbol with new keyword because symbol is not a constructor function. We can create a symbol by using the factory function Symbol(). It returns a unique symbol every time it is called.
var symbol = Symbol();
We can also add description to symbols. Symbol description does not have any functional value. They are used for debugging purpose, to differentiate between symbols.

var symbol1 = Symbol();//Symbol with no description
var symbol2 = Symbol('Symbol description');//Symbol with description
Enter fullscreen mode Exit fullscreen mode

Symbols are unique

Every time we create a new symbol in JavaScript, they return a unique value. Even though we get same output when we console.log symbol1 and symbol2, when we check if symbol1 is equal to symbol2 it returns false.

Image description

Symbol.for()

Symbol.for(key) is an inbuilt method in JavaScript. It searches for existing symbols in runtime-wide registry with the given key and returns it. If it is not found, it creates a new symbol with the given key. The key can also be used as the description of the symbol.

Image description

Why use Symbols?

  • We can use symbols as object properties

Image description

  • We can use symbols to avoid over writing object properties Say we have an object blackWidow with id and name properties.

code
As we can see the value of id property is changed. What if we don’t want to change the actual value of id we can add symbol in the object.

code

  • Symbols are hidden in loops and js functions. We can use them to keep any unique or identifier property hidden.

code

Top comments (0)