ES6 - Symbol.for()



This function creates a symbol and adds to registry. If the symbol is already present in the registry it will return the same; else a new symbol is created in the global symbol registry.

Syntax

Symbol.for(key) 

where, key is the identifier of the symbol

Example

The following example shows the difference between Symbol() and Symbol.for()

<script>
   const userId = Symbol.for('userId') // creates a new Symbol in registry
   const user_Id = Symbol.for('userId') // reuses already created Symbol
   console.log(userId == user_Id)    
   const studentId = Symbol("studentID") // creates symbol but not in registry
   const student_Id = Symbol.for("studentID")// creates a new Symbol in registry
   console.log(studentId == student_Id)
</script>

The output of the above code will be as shown below −

true
false
Advertisements