Introduction to Javascript Symbol Type

js

The symbol is a primitive datatype introduced in ECMAScript 2015. It is different from other data types in Javascript as its value is always unique and kept private for internal use. Symbols are only accessible from its reference after it is created.

Creating a Symbol

A symbol is created by calling Symbol() global factory function.

1
const mySym = Symbol();

Symbol() takes one optional parameter, which is a description of the symbol itself. Specifying a description while creating Symbols helps identify it during debugging.

1
2
const mySym = Symbol('name of person');
//Symbol(name of person)

The new keyword is not supported by Symbol(). The below code will throw a type error.

1
2
3
4
let sym = new Symbol();

// Uncaught TypeError: Symbol is not a constructor
// at new Symbol (<anonymous>)

Equality

Symbols are unique identifiers and are never equal to each other.

1
2
console.log(Symbol() === Symbol());
//false  

Symbols are useful for creating object properties as they are always unique, never equal to each other, thus avoiding name clashes.

1
2
3
4
5
6
7
const LESSON = Symbol();
const subject = {
  [LESSON]: 'Symbols on javascript'
}

subject[LESSON];
// "Symbols on javascript"

The symbol also prevents the overwriting of properties, intentionally or unintentionally as values created by Symbol() method is always unique.

Iterating over Symbol

Symbols are not enumerable i.e. they are not accessible by for...of or for...in methods. They will not be listed.

1
2
3
4
5
6
7
8
let obj = {};
obj[Symbol('one')] = 1;
obj[Symbol('two')] = 2;
obj['three'] = 3;
for (let i in obj) { 
console.log(i);
// three
}

Using typeof operator on Symbol

Using typeof operator you can identify symbols.

1
2
3
let sym = Symbol();
typeof sym;
// 'symbol'

Summary

In this article, we learned:

  • The symbol is a primitive datatype.
  • Symbols are always unique.
  • You can create a symbol by using Symbol() factory function.
  • Symbols are not enumerable.
  • You can use typeof operator to identify symbols.

Share and support us

Share on social media and help us reach more people