Skip to content

JavaScript Symbols

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.

Examples:

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 for..in 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.


→ Get my JavaScript Beginner's Handbook

→ I wrote 17 books to help you become a better developer:

  • C Handbook
  • Command Line Handbook
  • CSS Handbook
  • Express Handbook
  • Git Cheat Sheet
  • Go Handbook
  • HTML Handbook
  • JS Handbook
  • Laravel Handbook
  • Next.js Handbook
  • Node.js Handbook
  • PHP Handbook
  • Python Handbook
  • React Handbook
  • SQL Handbook
  • Svelte Handbook
  • Swift Handbook
...download them all now!

Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list