[Javascript] Symbol vs Symbol.for

Zhentiw發表於2024-03-22

Symbol.for("key")

Checks if a symbol with the key "key" already exists in the globals symbol registry.

If yes, it returns the existing symbol, otherwise, it creates a new symbol and adds it to the global regsitery.

Symbol("key")

Always creates a new, unique symbol that is different from any other symbol.

const one = Symbol.for("key")
const two = Symbol("key")
const three = Symbol.for("key")

console.log(one === two) // false
console.log(two === three) // false
console.log(one === three) // true
console.log(three === Symbol("key")) // false

相關文章