JavaScript introduced symbols in ES6 as a way to prevent property name collisions. As an added bonus, symbols also provide a way to simulate private properties in 2015-2019 JavaScript.

Introduction

The simplest way to create a symbol in JavaScript is to call the Symbol() function. The 2 key properties that makes symbols so special are:

  1. Symbols can be used as object keys. Only strings and symbols can be used as object keys.
  2. No two symbols are ever equal.
const symbol1 = Symbol();
const symbol2 = Symbol();

symbol1 === symbol2; // false

const obj = {};
obj[symbol1] = 'Hello';
obj[symbol2] = 'World';

obj[symbol1]; // 'Hello'
obj[symbol2]; // 'World'

Although the Symbol() call makes it look like symbols are objects, symbols are actually a primitive type in JavaScript. Using Symbol as a constructor with new throws an error.

const symbol1 = Symbol();

typeof symbol1; // 'symbol'
symbol1 instanceof Object; // false

// Throws "TypeError: Symbol is not a constructor"
new Symbol();

#javascript #es6 #programming #developer

A Practical Guide to Symbols in JavaScript
2.40 GEEK