Symbols in JavaScript

The datatype symbol is a primitive datatype along with null, undefined, number, string and boolean.

Symbols were introduced in the ECMAScript 2015 version in 2015.

Unlike like strings, numbers or booleans, symbols have no literals. They have to be created using the Symbol() function, the values returned as a result of calling this function is of type symbol.

The Symbol() function also has some static methods but is incomplete as a constructor so it cannot be used with the new keyword like this: new Symbol().

Creating and using a symbol

Every value returned from Symbol() is always unique, Hence no two symbols could ever have the same value.

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

The values returned from Symbol() can never be known as well:

const mySymbol = Symbol();
const mySecondSymbol = Symbol('this is a symbol');

console.log(mySymbol); // Symbol()
console.log(mySecondSymbol); // Symbol('this is a symbol')

Note: any value passed to the function is not the output value but more like an identifier or description of the symbol.

So symbols are a great way to create properties in an object to avoid clashing.

const propertyName = Symbol('unique property');
const myObject = {
	[propertyName]: 'This is a unique property',
 }
 console.log(myObject); // { Symbol(unique property): "This is a unique property" }
 console.log(myObject[propertyName]); // This is a unique property

A symbol property is not enumerable so they won't show in for...of and for...in loops. They will not appear in Object.keys() and Object.getOwnPropertyNames() as well.

There is, however, one method existing on the Object constructor: Object.getOwnPropertySymbols().

Object.getOwnPropertySymbols() returns an array of symbol properties on the object.

Symbol.for()

The Symbol.for() method searches for a specific symbol with the key provided, If the symbol does not exist, it creates a new one in the global symbol registry.

const firstSymbol = Symbol.for('mySymbol'); // creates symbol
const secondSymbol = Symbol.for('mySymbol'); // retrieves the symbol

firstSymbol === secondSymbol; // true

Since both variables point to the same symbol in memory, when compared, the result evaluates to true.

You can learn more about symbols here.

Found the article helpful?

Subscribe to my Newsletter to receive new articles in your inbox 👇

No spamming, just fresh articles straight out of the oven.