Javascript Do you know the Symbol type?

An introduction to the Symbol type introduced by ES2015

The type Symbol

Creating a Symbol

const myFirstSymbol = Symbol();
const foo = Symbol('foo');
console.log(foo); // Symbol(foo);
Symbol() === Symbol() // false
const a = Symbol('a');const otherA = Symbol('a');a === otherA // false

Characteristics of the type Symbol

const foo = Symbol('foo');console.log('This is the symbol foo: ' + foo); // Error

Accessing previously created Symbols

const foo = Symbol.for('foo');
const bar = Symbol.for('foo');foo === bar; // true
const foo = Symbol('foo');const bar = Symbol.for('foo');foo === bar; // false

Predefined Symbols

const arr = [1, 2, 3];const iterator = arr[Symbol.iterator]();console.log(iterator.next()); // {value: 'a', done: false}

Use cases for Symbol type

Image for post
Image for post
Photo by Daniel McCullough on Unsplash

Symbols as object property keys

const foo = Symbol();const myObject = {};myObject[foo] = 'foo';myObject['bar'] = 'bar';console.log(myObject); // {bar: "bar", Symbol(): "foo"}console.log(foo in myObject); // trueconsole.log(myObject[foo]); // 'foo'console.log(Object.getOwnPropertyNames(myObject)); // ['bar']console.log(Object.keys(myObject)); ['bar']
console.log(Reflect.ownKeys(myObject)); ['bar', Symbol]

Prevent collisions of property names

// Library Aconst jQuerySymbolA = Symbol('library a');
window[jQuerySymbolA] = $;
// Library Bconst jQuerySymbolB = Symbol('library b');
window[jQuerySymbolB] = $;

Final thoughts

Do you want to read more articles like this?

Written by

Entre paseo y paseo con Simba desarrollo en Symfony y React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store