Symbol Datatype in Javascript

Posted By : Dipak Kumar Singh | 27-Feb-2018

This blog post explains how Symbols work and use of Symbols. In ECMAScript 6 introduces a new primitive type: Symbols.

A new primitive type: Symbols

In ECMAScript 6 introduces a new primitive type: symbols. They are indications that serve as unique IDs. You create symbols through the factory function Symbol():

let symbolOne = Symbol();

Symbol() has an optional string-valued parameter that allows you give the newly created symbol a classification:

 

> let symbolTwo = Symbol('symbolTwo');
> String(
symbolTwo)
'Symbol(
symbolTwo)'

 

Each symbol returned via Symbol() is unique, each symbol has its own identity:

 

> symbolOne === symbolTwo

false

 

You can learn that symbols are primitive if you apply the kind of operator to one of them – it will return a new symbol-specific result:

 

> typeof symbolOne

'symbol'

 

Symbols can use as Object keys 


This is wherever Symbols get very impressive. They are heavily twisted with Objects. Symbols can be allowed as keys to Objects (set of like String keys), meaning you can allow an unlimited amount of unique Symbols to an object and be assured that these will not contend with String keys or other unique Symbols:

 
var obj = {};
var fooSym = Symbol('foo');
var otherSym = Symbol('bar');
obj['foo'] = 'bar';
obj[fooSym] = 'baz';
obj[otherSym] = 'bing';
assert(obj.foo === 'bar');
assert(obj[fooSym] === 'baz');
assert(obj[otherSym] === 'bing');
 

In extension to that, Symbols do not display up on an Object using for while, for of or Object.getOwnPropertyNames - the unique way to get the Symbols inside an Object is Object.getOwnPropertySymbols:

 
var fooSym = Symbol('foo');
var obj = {};
obj['foo'] = 'bar';
obj[fooSym] = 'baz';
Object.keys(obj); // -> [ 'foo' ]
Object.getOwnPropertyNames(obj); // -> [ 'foo' ]
Object.getOwnPropertySymbols(obj); // -> [ Symbol(foo) ]
assert(Object.getOwnPropertySymbols(obj)[0] === fooSym);
 

This suggests Symbols provide a whole new sense of meaning to Objects - they give a set of the stored underlayer to Objects - not iterable over, not obtained using the previously existing Reflection tools and proved not to compete with other properties in the object! 

About Author

Author Image
Dipak Kumar Singh

Dipak is a skilled HTML Developer, expertise in UI Development. Dipak likes watching movies and playing computer games.

Request for Proposal

Name is required

Comment is required

Sending message..