Symbol
A primitive type for creating unique identifiers, such as property keys that never collide with others.
- Returns
- A new, unique value of type
symbol.
Example
#const id1 = Symbol('id')
const id2 = Symbol('id')
console.log(id1 === id2)
console.log(typeof id1)
console.log(id1.description)
console.log(id1.toString())Definition and usage
#Symbol() creates a new, unique value of type symbol. Every call gives a different symbol, even with the same description: Symbol("id") === Symbol("id") returns false. The description in parentheses is only for debugging and is available through the description property.
Symbols are most often used as object property keys. Such a key never collides with any string or with a key added by other code, such as a library. Properties with symbol keys are skipped by Object.keys(), a for...in loop, and JSON.stringify(), so they work well for auxiliary data hidden from ordinary object inspection. They aren’t truly private, though, since Object.getOwnPropertySymbols() can read them.
The language also has built-in symbols that let you change how your own objects behave. Symbol.iterator makes an object work with for...of, and Symbol.toPrimitive controls how an object converts to a number or a string. Symbol.for("key") returns a symbol from the global registry, the same one for the same key across the whole application. You don’t create a symbol with new.
Syntax
#Symbol()
Symbol(description)
Symbol.for(key)
const obj = { [symbol]: value }
obj[symbol]Parameters
#description
optional string
A description visible in the console and in thedescriptionproperty. It has no effect on the symbol’s uniqueness.
More examples
#const internalId = Symbol('internalId')
const student = { name: 'Emma', [internalId]: 42 }
console.log(student[internalId])
console.log(Object.keys(student))
console.log(JSON.stringify(student))
console.log(Object.getOwnPropertySymbols(student))const a = Symbol.for('app.theme')
const b = Symbol.for('app.theme')
console.log(a === b)
console.log(Symbol.keyFor(a))
console.log(Symbol('app.theme') === a)class Score {
constructor(points) {
this.points = points
}
[Symbol.toPrimitive](hint) {
return hint === 'number' ? this.points : `${this.points} pts`
}
}
const score = new Score(120)
console.log(+score)
console.log(`${score}`)
console.log(score * 2)The engine calls the [Symbol.toPrimitive] method every time it converts the object to a primitive value. The hint argument says whether it needs a number ("number"), a string ("string"), or doesn’t care ("default").
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- A symbol doesn’t give you real privacy. For hidden data in classes, use private fields
#field. - Don’t create a symbol with
new Symbol(), since that throws aTypeError. A symbol is a primitive value, just like a number or a string. - A symbol doesn’t convert to a string on its own:
"id: " + Symbol("x")throws aTypeError. Usesymbol.toString()orsymbol.description.
Related entries
#- Iterators (Symbol.iterator)The iteration protocol: an object with a [Symbol.iterator]() method works with for...of, spread, and destructuring.
- #fieldFields and methods prefixed with # are private: only code inside the class can access them.
- Object.keys()Returns an array of an object’s own, enumerable property names.
- typeofReturns a string with the name of a value’s type, e.g. "number", "string", or "object".
- JSON.stringify()Converts a JavaScript value, such as an object or array, into a string in JSON format.
Spotted a mistake or missing an example? Write to us.