Open In App

Motivation to bring symbols in ES6

Javascript comprised six datatypes undefined, null, boolean, String, Number and Object (includes array datatype). The Symbol is newly introduced datatype in ES6 also known as JavaScript 6, which makes the total number of data types in JavaScript is 7. It is a primitive datatype which means Symbol cannot be instantiated. Symbols are immutable datatype and act as unique identifiers for object keys. Before the introduction of Symbol, it was very difficult to generate unique object keys. It was important to maintain unique object keys to prevent the overwriting of values having similar object key as this could result in loss of data. The introduction of Symbol helped overcome this problem as unique keys could be generated without writing a complicated piece of code. Unique object keys can be generated using Symbol() function. The Symbol() function returns a value of type symbol. Given below are examples that demonstrate the purpose of symbols.

Syntax:



let symbol = Symbol();

Example 1: In this example, we are going to generate symbols.

Example 2: In this example we will see Symbol() function generates unique object keys .



Note: Symbol datatype is primitive datatype and cannot be instantiated

Comparison of Symbol and without Symbol: Let us consider an example where a list of marks obtained by students in a particular exam needs to be maintained. The students are yet to be assigned their roll numbers. In this situation, the name of a student is to be used as an object key. However, there can be more than one student with similar names. This can cause overwriting of marks obtained by each student resulting in data loss. To overcome this problem symbol datatype can be used.

Limitations of Symbol:


Article Tags :