Skip to content

JavaScript Symbols

New Course Coming Soon:

Get Really Good at Git

An easy to follow tutorial to understand JavaScript Symbols

Symbol is a primitive data type of JavaScript, along with string, number, boolean, null and undefined.

It was introduced in ECMAScript 2015, so just a few years ago.

It’s a very peculiar data type. Once you create a symbol, its value is kept private and for internal use.

All that remains after the creation is the symbol reference.

You create a symbol by calling the Symbol() global factory function:

const mySymbol = Symbol()

Every time you invoke Symbol() we get a new and unique symbol, guaranteed to be different from all other symbols:

Symbol() === Symbol() //false

You can pass a parameter to Symbol(), and that is used as the symbol description, useful just for debugging purposes:

console.log(Symbol()) //Symbol()
console.log(Symbol('Some Test')) //Symbol(Some Test)

Symbols are often used to identify object properties.

Often to avoid name clashing between properties, since no symbol is equal to another.

Or to add properties that the user cannot overwrite, intentionally or without realizing.


const NAME = Symbol()
const person = {
  [NAME]: 'Flavio'

person[NAME] //'Flavio'

const RUN = Symbol()
person[RUN] = () => 'Person is running'
console.log(person[RUN]()) //'Person is running'

Symbols are not enumerated, which means that they do not get included in a for..of or loop ran upon an object.

Symbols are not part of the Object.keys() or Object.getOwnPropertyNames() result.

You can access all the symbols assigned to an object using the Object.getOwnPropertySymbols() method.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: