OneCompiler

Symbol data type in Javascript

545

What is Symbol datatype

Symbol datatype is a primitive data type which is used for creating unique identifiers. Once a symbol is created, it's value will be private and internal to that program alone as you can not access it from other programs. It was introduced in ECMAScript 2015.

Consider if you want to modify something in a third party code which is shared, you can not just add fields which they might also be using. If you use symbol then you will not break their code and your symbols will be used ineternal to you which works for both the parties with out any conflicts.

How to create symbol?

Symbol() method is used to create a symbol identifier. You can also provide a optional parameter to it which used as a description to the symbol created. This will be helpful for debugging purposes.

let pid = Symbol();
let pid2 = Symbol('sample symbol'); 

Why Symbols are used?

  • To identify Object properties.
  • Symbols are unique. Even if you create two symbols with same description, their value will be definetely unique.
  • To protect Object properties from over-writing.

How to access symbols assigned to an Object?

  • Object.getOwnPropertySymbols() method is used to access symbols assigned to an object.
  • Note that you can not access symbols using for..of or for..in loops.
  • Reflect.ownKeys(obj) method returns all keys of an object including symbols.