JavaScript Symbols
Description
These are tokens that serve as unique IDs. You create symbols via the
factory function Symbol()
(which is loosely similar to
string returning strings if called as a
function).
Syntax
const symbol1 = Symbol()
Add a description
const tralala = Symbol("tralala")
console.log(tralala) // Symbol(tralala)
Convert to string
const tralala = Symbol("tralala")
console.log(String(tralala)) // `Symbol(tralala)`
Every Symbol is unique
console.log(Symbol() === Symbol()) // false
Property keys
const KEY = Symbol()
const obj = {}
obj[KEY] = 123
console.log(obj[KEY]) // 123
const FOO = Symbol()
const obj = {
[FOO]() {
return "bar"
},
}
console.log(obj[FOO]()) // bar
Use as reserved inherited method names
If for some bizarre reason you want to use reserved inherited method names yourself (like toString) you can with Symbols.
Syntax
const toStringSymbol = Symbol("toString")
Array.prototype[toStringSymbol] = function () {
return `${this.length} cm of blue yarn`
}
console.log([1, 2].toString()) //1, 2
console.log([1, 2][toStringSymbol]()) // 2 cm of blue yarn
Expressions
Symbols can also be used in object expressions and classes.
const toStringSymbol = Symbol("toString")
let stringObject = {
[toStringSymbol]() {
return "a jute rope"
},
}
console.log(stringObject[toStringSymbol]()) // a jute rope