Shedding light on a newer JavaScript primitive

A Quick Look at JavaScript Symbols

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)

output:
true

In this case, the two boolean values, x and y here are equal.

let a = Symbol()
let b = Symbol()
console.log(a === b)

output:
false

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.

Use case

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.

userFromApi:
{
id: 143,
firstName: 'Simon',
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
console.log("userFromApi", userFromApi)

output:

{
"id": 143,
"firstName": "Simon",
"lastName": "Le Bon",
Symbol(id): 32415343534
}

The Symbol(id) key is now present. Then, if we console.log:

console.log(userFromApi[idSym])

output:

32415343534
Simon Le Bon

References:

https://www.youtube.com/watch?v=4J5hnOCj69w
https://javascript.info/symbol
https://developer.mozilla.org/en-US/docs/Glossary/symbol