Generator Functions — JS Technical Interview Questions & Answers

function* and yield for pausable functions.

Generator Functions

  • Generator Functions (js generators) is a JS topic. In plain words you use it for add(a, b) in a checkout total. Don’t start with a slogan — start with that picture.
  • Smallest example: function add / const add = () =>. Type it, run it, and say what you see. If you can do that from memory, you know Generator Functions (js generators).
  • From the example next to this theory: function* and yield for pausable functions.
  • Trap: this surprise in arrow vs function. Fix that before you talk about advanced JS.
  • Viva: what is Generator Functions (js generators)? Then show function add / const add = () =>. Then name the trap.

Technical Interview Tip: What is Generator Functions (js generators)? Show this: function add / const add = () =>. Trap: this surprise in arrow vs function.

Code Examples for Generator Functions

Generator Functions — working example

const double = (n) => n * 2;
const inc = (n) => n + 1;
const compose = (f, g) => (x) => f(g(x));
console.log(compose(double, inc)(3)); // double(inc(3)) = 8

function* ids() {
  yield 1;
  yield 2;
}
console.log([...ids()]);

function memoize(fn) {
  const cache = new Map();
  return (x) => {
    if (cache.has(x)) return cache.get(x);
    const y = fn(x);
    cache.set(x, y);
    return y;
  };
}
const slowSquare = memoize((n) => n * n);
console.log(slowSquare(9), slowSquare(9));

console.log("A");
setTimeout(() => console.log("C"), 0);
Promise.resolve().then(() => console.log("B"));
// Order: A, B, C

Generator Functions — compose pipelines; generators pause with yield; memoize caches; async work is scheduled via the event loop.

How to Explain Generator Functions to an Interviewer

What is Generator Functions (js generators)?

Used for add(a, b) a checkout total Not just the heading

Give one small example of Generator Functions (js generators).

function add / const add = () => function* and yield for pausable functions

What mistake do beginners make with Generator Functions (js generators)?

this surprise in arrow vs function Show the fix

Where do you use Generator Functions (js generators)?

a checkout total add(a, b)