JavaScript Symbols Simply Explained

JavaScript

11/09/2021


Symbols are primitives that serve as unique identifiers.

JAVASCRIPT
const symbol1 = Symbol()
const symbol2 = Symbol()
console.log(symbol1 === symbol2) // false

Comparing two Symbols that appear identical will actually equate to false as they are both different. No two Symbols are ever the same.

JAVASCRIPT
const symbol3 = Symbol("Bananas")
console.log(symbol2) // Symbol()
console.log(symbol3) // Symbol("Bananas")

You may add a string between the parentheses of the constructor. However, this only serves as a descriptor for the developer.

JAVASCRIPT
new Symbol("12 Bananas") // Uncaught TypeError: Symbol is not a constructor

And despite being called a "constructor", it doesn't actually work with the new keyword.

Use cases

There are 2 common use cases for Symbols.

Property keys

Symbols are frequently used as keys in objects as they ensure that the property value is never unintentionally overwritten.

JAVASCRIPT
let person = {
name: "Jack"
}
const name = Symbol("name")
person[name] = "Donny"
console.log(person) // Object { name: "Jack", Symbol("name"): "Donny" }

Even when attempting to overwrite the name property inside the person object, the new value is assigned to a new key instead. If you wish to add a symbol inline, make sure to surround with it square brackets.

JAVASCRIPT
person = {
name: "Jack",
[name]: "Donny"
}

As constants

Another frequent use case for Symbols are constants, i.e. unique concepts. We often identify these through strings, but how about Symbols?

JAVASCRIPT
const BANANA = Symbol("Banana")
const APPLE = Symbol("Apple")
function identifyFruit(fruit) {
switch (fruit) {
case BANANA:
return "This whole thing is bananas!"
case APPLE:
return "An apple a day keeps the doctor away."
default:
return "Not a supported fruit!"
}
}
identifyFruit(BANANA) // "This whole thing is bananas!"
identifyFruit("Apple") // "Not a supported fruit!"

By using Symbols, we can avoid any mixup between variables that have the same string value, but different semantic meanings depending on the context. For instance, Apple might refer to the company and not the actual fruit.


WRITTEN BY

Code and stuff