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.
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:
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