- Like strings or UIDs, but guaranteed to be unique
- (almost) private
Symbols have nothing to do with Ruby symbols (:ruby_symbol)
Create symbols (don't use new
!)
Symbol() === Symbol() // false
You can associate a symbol with a string for debugging purposes
Symbol('foo') === Symbol('foo') // false
console.log(Symbol('foo')) // "Symbol('foo')"
One use case: Use like private properties for encapsulation
const privateMethodKey = Symbol('privateMethod')
class Foo {
constructor(){
this[privateMethodKey] = () => 42
}
sayHello(){
console.log('hi')
}
}
What will this code print?
const foo = new Foo()
const newSymbol = Symbol('privateMethodKey')
console.log(Object.keys(foo))
console.log(foo[newSymbol])
console.log(foo[privateMethodKey])
- used internally in JS (example:
Symbol.iterator
) - use like enums
- monkey patching