Javascript ES6 Symbol Type code examples | Typescript

In this tutorial, we will delve into learning the basics of the Symbol primitive data type with examples.

JavaScript ES6 Symbol Data Type

The symbol is a primitive data type introduced with ES6 or ECMAScript 2015 in JavaScript. TypeScript also supports this Symbol as a primitive data type, similar to String, number, and Boolean.

Symbol is a special primitive type that represents unique values or keys of an object. It is used to identify unique objects with symbol objects. Symbol variables always return a new unique value. All the examples provided below are applicable in both JavaScript and TypeScript.

How to Create and Initialize Symbols

A Symbol object is created as follows:

It creates a unique name value for every object creation. An empty Symbol is created by the Symbol() constructor.

var symboleObj = Symbol();
console.log(symboleObj); //Symbol()
console.log(typeof symboleObj); //symbol

You can also supply a key to the Symbol function as seen in the example below:

var symbolObj1 = Symbol("keyhere");
console.log(symbolObj1); // Symbol(keyhere)

Comparing Symbols for Uniqueness in JavaScript

The same Symbol with the same key always returns the same value. Objects with the same value return true.

Using == checks and returns true.

let symbolObj1 = Symbol("s1");
let symbolObj2 = Symbol("s1");
console.log(symbolObj1 == symbolObj2); // false

Using Key as a Symbol in Objects

Symbols can be stored in objects as keys. The value can be retrieved as normal keys. Object.keys and Object.getOwnPropertyNames will not get the Symbol Keys, meaning Keys are not iterable in for…in and for..of iteration processes.

Hence, to retrieve symbol keys, Object.getOwnPropertySymbols is used.

var symbolObj = Symbol();
let myObject = {
  [symbolObj]: "myvalue",
  key1: "value1",
};
console.log(myObject); // Object Symbol(): "myvalue"

console.log(myObject[symbolObj]); // myvalue
console.log(Object.keys(myObject)); // return [ 'key1' ]
console.log(Object.getOwnPropertyNames(myObject)); // return [ 'key1' ]
console.log(Object.getOwnPropertySymbols(myObject)); // return [ Symbol() ]

Converting Symbol to String in JavaScript ES6

The toString() method returns the string version of the Symbol object.

It also converts to String using String(symbolObj). If you use new String(symbolObj), it throws Uncaught TypeError: Cannot convert a Symbol value to a string

var symbolObj = Symbol();
console.log(String(symbolObj)); // myvalue
console.log(symbolObj.toString()); // myvalue

Converting Symbol to Boolean in JavaScript ES6

Pass the Symbol object to the Boolean class, which always returns true. It can also be used with the ! not operator to return false.

var symbolObj = Symbol(123);
console.log(new Boolean(symbolObj)); // true
console.log(!symbolObj); // false

Symbol for Method Example

Each symbol is created and registered in the global scope. The for() method takes an input string - a description which searches the global scope for Symbols for the given description and returns the Symbol.

let test = Symbol.for("test");
console.log(test === test); // true

Converting Symbol to Number In JavaScript

To convert Symbol to a number in JavaScript, please follow the steps below:

  • Use the Number Constructor with the given symbol object.
  • If the same code is used for Number like new Number(symbolObj), it gives a compilation Error: Cannot convert a Symbol value to a number.
  • Pass different values to avoid the error.

JavaScript ES6 Pre-built Symbols

JavaScript and TypeScript define native symbols as part of the language. Symbol.iterator Example This returns the iteration for an object that can be used for loop syntax. Here is an example of String’s iteration of an object:

interface IIterationString {
  [Symbol.iterator](): IterableIterator;
}

class StringIteration implements IIterationString {
    private strings = ['one', 'two', 'three'];

    constructor() {}

    *[Symbol.iterator]() {
        for(let ss of this.strings) {
            yield ss;
        }
    }
}

for(let elem of (new StringIteration())) {
    console.log(elem); // returns one two three
}