點燈坊

失くすものさえない今が強くなるチャンスよ

Symbol Overview

Sam Xiao's Avatar 2021-11-25

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.

overview000

let s = new Symbol () // ?

Symbol can’t be created by new, since Symbol is not a constructor function.

overview001

toString

let s = Symbol () // ?
s.toString () // ?
console.log (s)
  • Symbol provides toString to transform Symbol into String; its value is Symbol()
  • If we use console.log to show Symbol, it will use toString to transform into String first and then show the result

overview002

===

let s1 = Symbol ()
let s2 = Symbol ()

s1 === s2 // ?

Symbol always returns unique value.

overview003

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.

overview004

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.

overview005

Conclusion

  • The concept of Symbol is simple; it’s just a type for the unique value