Introduction to Javascript Symbol Type

js.Srijan

Table of Contents

Introduction

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.

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.

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.

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.

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.

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.

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.

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 this

Share on social media