A Symbol represents a unique identifier. It may be used as a unique identifier for an object’s key. This is the data type’s primary purpose.
To better understand, let’s compare two Boolean variables:
let x = true
let y = true
console.log(x === y)
In this case, the two boolean values, x and y here are equal.
let a = Symbol()
let b = Symbol()
console.log(a === b)
But in this case, a and b here are not equal. This is because Symbols represent unique values.
Optionally, we can pass a label when creating a Symbol:
let sku = Symbol("sku")
Here, we pass the the “sku” label when creating the sku symbol. The label has no impact on the unique value of the symbol and is used only for debugging purposes. The underlying unique value associated with the Symbol cannot be displayed. Think of it as a GUID.
Let’s say we receive a user object from API call that we want to assign a unique identifier to it from our own front end system. We do not want to overwrite the original object’s id property with our system identifier.
lastName: 'Le Bon'
To be sure not to overwrite the original object’s id property with our own, we can create a Symbol called “idSym”, and assign an ‘id’ label to it:
const idSym = Symbol('id')
Then we can create a new key-value pair in the userFromApi object, with the key being our new symbol and the value being the id from our front end system.
userFromApi[idSym] = 32415343534 // our id for user
"lastName": "Le Bon",
The Symbol(id) key is now present. Then, if we console.log: