JavaScript - Symbols

Madhusudhana Dollu

JavaScript Developer

Outline

  • What are Symbols?
  • The motivation for bringing symbols.

  • Symbols with description vs key

  • Symbols as object properties

  • Symbols defined by the standard

    • Iterables and Symbol.iterator, Symbol.asyncIterator

    • Other symbols: Symbol.match, Symbol.search

  • Using symbols in practice

  • Q & A.

What are Symbols?

Symbols are like unique tokens

Every new symbol is a new reference

and they are not objects

let s1 = Symbol();

let s2 = Symbol('my sym');

let s3 = Symbol('my sym');

s1 === s2; // false

s2 === s3; // false

unlike other types, new keyword is allowed while creating symbol as it supposed to return object.

The Motivation

Symbol Registry

Unlike the unique symbols defined by Symbol(), symbols in the symbol registry are shared

let s1 = Symbol.for('key');

Symbols as Object properties

let obj = {};

obj['prop1'] = 'value';

 

let s1 = Symbol();

obj[s1] = 'value for sym prop';

for(let key in obj) {

    console.log(obj[key]);

}

Standard Symbols

Symbol.iterator

Symbol.asyncIterator

Symbol.match

Symbol.search

Symbol.replace

...

Symbol.iterator

Codepen Demos

Symbols in practice

Questions?

Made with Slides.com