Open In App

Motivation to bring symbols in ES6

Last Updated : 20 Mar, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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.

  • Code:




    <script>
      
        // Write Javascript code here
        let sym1 = Symbol()
        let sym2 = Symbol('mysymbol')
        console.log('Type of sym1: ', typeof(sym1))
        console.log('Type of sym2: ', typeof(sym2))
    </script>

    
    

  • Output:
    Type of sym1:  symbol
    Type of sym2:  symbol

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

  • Code:




    <script>
      
        // Write Javascript code here
        let sym1 = Symbol('mysymbol')
        let sym2 = Symbol('mysymbol')
        console.log('sym1===sym2: ', sym1===sym2)
    </script>

    
    

  • Output:
    sym1===sym2: false

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.

  • Code 1: The code snippet below shows the scenario when symbol is not used.




    <script>
      
    // Write Javascript code here
    var marks = {}
    marks["Joe"] = 100
    marks["Ana"] = 90
    marks["Chloe"] = 95
    marks["Marie"] = 75
    console.log(marks)
    console.log('Another student with'
              + ' name Chloe appears')
    marks['Chloe'] = 60
    console.log('After the marks of the'
         + ' fifth student is entered')
    console.log(marks)
    </script>

    
    

  • Output: The marks of Chloe gets overwritten when another student with same name appears.
  • Code 2: The code snippet below shows the scenario when symbol is used




    <script>
      
    // Write Javascript code here
    var marks={}
    var sym1=Symbol("Joe")
    marks[sym1]=100
    var sym2=Symbol("Ana")
    marks[sym2]=90
    var sym3=Symbol("Chloe")
    marks[sym3]=95
    var sym4=Symbol("Marie")
    marks[sym4]=75
    console.log(marks)
    console.log('Another student '
        + 'with name Chloe appears')
    var sym5=Symbol("Chloe")
    marks[sym5]=60
    console.log('After the marks of '
        + 'the fifth student is entered')
    console.log(marks)
    </script>

    
    

  • Output: The marks of Chloe does not get overwritten when another student with same name appears, no data is lost. You have to run this locally.

Limitations of Symbol:

  • Symbols are ignored in for..in loop.
  • Ignored by functions such as Object.keys(), Object.getOwnPropertyNames() and JSON.stringify() and hence cannot be serialized.
  • Symbol was primarily used to ensure privacy. But methods like Object.getOwnPropertySymbols() returns an array of any symbol-based keys and Reflect.ownKeys() returns an array of all keys, including symbols.


Similar Reads

What is the motivation for using React Redux?
React Redux makes handling data in big applications easier. It acts like a connection between different parts of your app (React components) and a central place where all the important data is stored (Redux). This ensures everyone is working with the same up-to-date information, making your app organized and development smoother. Features of React
2 min read
D3.js Symbols symbolDiamond Property
The d3.symbolDiamond property is a symbol type in D3.js. It is a diamond-shaped symbol type that can be used. Syntax: d3.symbolDiamond Example 1: C/C++ Code &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;script src= &quot;https://d3js.org/d3.v5.min.js&quot;&gt; &lt;/script&gt; &lt;/head&gt; &lt;body&gt;
1 min read
CSS additive-symbols Descriptor
CSS additive-symbols descriptor is mainly used to specify symbols when the value of a counter system descriptor is additive. It defines additive tuples, each of which is a pair containing a symbol and a non-negative integer weight. Syntax: additive-symbols : positiveIntegerCounter identifier(s)/string(s)/image(s); Property values: There are a few i
1 min read
D3.js Symbols symbolCross Property
The d3.symbolCross property is a symbol type in D3.js. It is a cross-shaped symbol type that can be used. Syntax: d3.symbolCross Example 1: C/C++ Code &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;script src= &quot;https://d3js.org/d3.v5.min.js&quot;&gt; &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h1
1 min read
D3.js Symbols symbolSquare Property
The d3.symbolSquare property is a symbol type in D3.js. It is a square-shaped symbol type that can be used. Syntax: d3.symbolSquare Example 1: C/C++ Code &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;script src= &quot;https://d3js.org/d3.v5.min.js&quot;&gt; &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;
1 min read
HTML Symbols
there are some characters in html those are reserved, they have special meaning when they used in an html document. Like if you used less than or greater than sign in your html document then the browser will treat them differently special symbols &copy;:copyright sign Syntax : &amp;copy; code : &lt;p&gt;these is the sign of : &amp;copy;&lt;/p&gt;
6 min read
D3.js Shapes Symbols API Complete Reference
The D3 is an abbreviation of Data-Driven Documents, and D3.js is a resource JavaScript library for managing documents based on data. D3 is one of the most effective frameworks to work on data visualization. Shapes Symbols Description D3.js symbol() FunctionThe d3.symbol() method constructs a new symbol generator with the default settings. D3.js sym
2 min read
How to filter an array of objects in ES6 ?
In this article, we will try to understand how we could filter out or separate certain data from the array of objects in ES6. Let us first try to understand how we could create an array of objects by following certain syntax provided by JavaScript. Javascript Array of Objects: The array of objects helps any user to store multiple values in a single
4 min read
ES6 RegEx
A RegEx is the short form of the Regular Expression, which is the sequence of characters that define a pattern. The characters in a RegEx can be alphabets, numbers or special characters. Usually, RegEx is used to find a pattern in a string to replace, delete or modify them. In ES6, a RegEx can be defined by 2 different notations. Literal notation:
3 min read
Arrow operator in ES6 of JavaScript
ES6 has come with various advantages and one of them is the arrow operator. It has reduced the function defining code size so it is one of the trending questions asked in the interview. Let us have a deeper dive into the arrow operator's functioning. Syntax: In ES5 a function is defined by the following syntax: function functionName(arg1, arg2….) {
4 min read