JavaScript(ES6) Symbols
Puja Kundu
Posted on June 21, 2022
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
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.
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.
Why use Symbols?
- We can use symbols as object properties
- We can use symbols to avoid over writing object properties Say we have an object blackWidow with id and name properties.
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.
- Symbols are hidden in loops and js functions. We can use them to keep any unique or identifier property hidden.
Posted on June 21, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
March 28, 2023