JS symbol

Seonglae Cho
2 min readMay 27, 2021

--

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!"
blablable.blablaProtocol()
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.

Symbol.for('blabla')
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

--

--

No responses yet