Javascript Generators
Why we have Generators in Javascript?
Generators provide a way to pause and resume execution of a function and can yield multiple values. They are a powerful, versatile feature of JavaScript, although they are not commonly used.
Each Generator Function returns Generator Object has main 3 components:
- “NEXT” advances, we manually iterated through the
Generatorobject, - “YIELD” pauses, can pause a generator function and return the value that follows
yield - “RETURN” stops, the generator can be terminated at any point.
function* generateLog() {
console.log("Running...")
yield "PAUSED"
console.log("Running Again...")
return "STOPPED"
}
/* Output:
Running...
{ value: 'PAUSED', done: false }
Running Again...
{ value: 'STOPPED', done: true }
*/Generator is a type of Iterator, has a next method returns: { value, done }. They allow you to define an iterative algorithm by writing a single function(FUNCTION*). Long story short, It is easy way to create custom Iterator objects.
iterator.next() // { value: 1, done: false }
iterator.next() // { value: 2, done: false }
iterator.next() // { value: 3, done: false }
...
iterator.next() // { value: undefined, done: true}It has some advantages:
Lazy Evaluation:
Get Nazar Pashazade’s stories in your inbox
Join Medium for free to get updates from this writer.
It delays the execution of an expression until its value is needed. In this example value will be generated as required even there is infinitive loop.
function* generateId() {
let id = 1
while (true) {
yield id++
}
}
const idGenerator= generateId()
idGenerator.next() // { value: 1, done: false }
idGenerator.next() // { value: 2, done: false }
idGenerator.next() // { value: 3, done: false }
// etc ...Memory Efficient
The only values generated are those that are needed.
It is possible to pass value to .next(input)
In this example we are listening infinitively by next():
function* listener() {
console.log("Listening...")
while (true) {
const message = yield
console.log("Heard: ", message)
}
}
const l = listener()
console.log(l.next("Hey"))
console.log(l.next("How are you?"))
console.log(l.next("Etc.."))
// Listening...
// Hey
// Heard: How are you?
// // Heard: Etc..State Machine
It can be used as state machine, because, generators remember where they were last time.
function* bacnkAccount() {
let balance = 0
while (balance >= 0) {
balance += yield balance
}
return "Bankrupt"
}
const account = bacnkAccount()
account.next() // { value: 0, done: false }
account.next(10) // { value: 10, done: false }
account.next(20) // { value: 30, done: false }
account.next(30) // { value: 60, done: false }







