🟔 MediumModern JSšŸ“– Theory Question

What are generators and when would you use them?

šŸ’”

Hint

function* that can yield values lazily; returns an iterator

Full Answer

Generators (function*) can pause execution and yield values one at a time.

function* range(start, end) {
  for (let i = start; i <= end; i++) yield i;
}
for (const num of range(1, 5)) console.log(num); // 1,2,3,4,5

// Infinite lazy sequence
function* naturals() {
  let n = 0;
  while (true) yield n++;
}

Use cases: lazy/infinite sequences, custom iterators, Redux-Saga uses generators for async flows.

More Modern JS Questions

🟢 EasyWhat is optional chaining (?.) and nullish coalescing (??)?ā†’šŸŸ¢ EasyWhat are tagged template literals and what are they used for?ā†’šŸŸ¢ EasyExplain destructuring for objects and arrays — including defaults, renaming, rest, and nesting.ā†’šŸŸ¢ EasyWhat are Symbols and what are their main use cases?→

Practice this in a timed sprint →

5 free questions, no signup required

⚔ Start Sprint