Symbol is a new type for unique value in ECMAScript 2015.
Version
ECMAScript 2015
Symbol
let s = Symbol () // ?
typeof s // ?
Symbol can be created by Symbol
, and its type is symbol
.
let s = new Symbol () // ?
Symbol can’t be created by new
, since Symbol
is not a constructor function.
toString
let s = Symbol () // ?
s.toString () // ?
console.log (s)
- Symbol provides
toString
to transform Symbol into String; its value isSymbol()
- If we use
console.log
to show Symbol, it will usetoString
to transform into String first and then show the result
===
let s1 = Symbol ()
let s2 = Symbol ()
s1 === s2 // ?
Symbol
always returns unique value.
let s1 = Symbol ('Sam')
let s2 = Symbol ('Sam')
s1 === s2 // ?
We can provide String to Symbol
, but it’s just for description. Symbol
still returns a unique value.
let s1 = Symbol.for ('Sam')
let s2 = Symbol.for ('Sam')
s1 === s2 // ?
If we want same description represents the same value, we can Symbol.for
instead of Symbol
.
Conclusion
- The concept of Symbol is simple; it’s just a type for the unique value