JS symbol

This is JS Symbol Docuemnt

Javascript implements iteration(for and for await and so on..) by setting Iterable protocol using Symbol Symbol.iterator and Symbol.asyncIterator

for example

const iterable = {}iterable1[Symbol.iterator] = function* () {
yield 1
yield 2
yield 3
for (const a of iterable) console.log(a)// 1
// 2
// 3

There is more information

There is Local Symbol and Global Symbol

Local Symbol

let’s make one simple js custom protocol by using local symbol

object prototype is not recommended (you’re case will be class or function) but for example

const symbol = Symbol('blabla')Object.prototype.blablaProtocol = function(){
const symbol = Symbol.for('blabla')
if (this[symbol] !== undefined) console.log(this[symbol])
else throw new Error()
// just do something with that

and make instance like this

const blablable = {}
const another = {}
blablable[symbol] = "hello protocol!"
another.blablaProtocol() // Error

Global Symbol

Symbol.for is static method to make and get global symbol which return global symbol with given key or make new symbol

let’s see a code

symbol = Symbol.for('blabla')
symbol === Symbol.for('blabla') // true
Symbol('blabla') === Symbol.for('blabla') // false

Global symbol is stored in GSR(global symbol registry) which are managed by JS Engine. So Global symbol can be accessed by another window like iframe

You can implement compare variable like this.

const ADMIN = Symbol.for('blabla')

There is many ways to make unique variable, but symbol is very basic and native way to make unique variable



www.seongland.com next.seongland.com github.com/seonglae

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