Code Logo

Range with Generator Function

Published at25 Jul 2026
JavaScript Functions Hard 0 views
Like0

Write a JavaScript generator function that takes a start and end value, yields each integer in that range, and returns the values as an array. Use the function* syntax with yield to produce values lazily.

Generator functions in JavaScript are defined with function* syntax and use the yield keyword to pause and resume execution. Each call to the generator's .next() method executes until the next yield statement, returning an object { value, done }. Generator functions can produce infinite sequences lazily because values are computed only when requested.

Generators are a powerful JavaScript feature for lazy evaluation, custom iteration, and managing asynchronous flow. They implement the iterator protocol (Symbol.iterator) and can be used with for-of loops and spread operators. The Array.from() method can consume a generator to produce an array: Array.from(gen()).

Time complexity is O(n) for consuming all yielded values, where n is the range size. Each yield pauses and resumes the generator function. Space complexity is O(1) for the generator state, O(n) for the collected array.

Edge cases include empty ranges (start >= end, generator yields nothing), single-element ranges, negative values, and ensuring the generator correctly handles the inclusive start and exclusive end convention.

Example Input & Output

Example 1
Input
0,3
Output
[0,1,2]
Explanation

Range 0 to 2

Example 2
Input
5,5
Output
[]
Explanation

Empty range (start equals end)

Example 3
Input
1,5
Output
[1,2,3,4]
Explanation

Range 1 to 4

Example 4
Input
10,13
Output
[10,11,12]
Explanation

Three elements

Example 5
Input
-2,2
Output
[-2,-1,0,1]
Explanation

Negative to positive

Algorithm Flow

Recommendation Algorithm Flow for Range with Generator Function

Solution Approach

Create a generator function that yields a range of numbers using the function* syntax and yield keyword. Generators can pause and resume execution, producing a sequence of values lazily.

function* range(start, end) { for (var i = start; i <= end; i++) yield i; }

Calling a generator returns an iterator. Use for...of to consume values, or call next() manually. Generators are useful for lazy sequences and infinite lists.

Time O(1) per yield, Space O(1).

Best Answers

javascript - Approach 1
function* range(start, end) {
  for (var i = start; i < end; i++) {
    yield i;
  }
}

function solution(start, end) {
  return Array.from(range(start, end));
}