Generators in JavaScript

Generators in JavaScript

What is a generator?

  • A generator function in JavaScript is a special type of function which is able to stop and resume its execution at will.

generator function syntax

  • To create a generator function we put a star * after the function keyword
  • Arrow generator functions are not permitted
  • Inside the function we can use yield to pause the execution
function* generate() {
  yield 33;
  yield 99;
}
  • yield pauses the execution and returns a so called Generator object to the caller.
  • This object is both an iterable, and an iterator at the same time.

Note: generators go exhaust once you consume all their values.

generator with for...of loop

  • Let's write a simple function which generates n numbers

function* generateNumbers(limit=Infinity){
  for(let i=1; i <= limit; i++){
    yield i;
  }
}

// let's create generator
let gen = generateNumbers(2);

// let's use for...of
for(const num of gen){
  console.log(num);
}
// output
// 1
// 2
- From the above code let gen = generateNumbers(2); we have created a generator object which generates 2 numbers. - After, we used it with for...of construct and logged the number to the console.

generator with spread (...) operator

function* fibonacci(limit=Infinity) {
  let count = 1;
  let a = 0;
  let b = 1;
  while (count <= limit) {
    let current = a;
    a = b;
    b = current + a;
    yield current;
  }
}

let fib = fibonacci(3);
console.log(...fib)
// output: 
- In the above code we have written fibonacci generator which creates n number of fibonacci numbers. - with let fib = fibonacci(3); , we have created the fib generator and used it with spread ... operator. - we can use the generator as Iterator

References: