Code Logo

Custom Iterator with Symbol

Published at25 Jul 2026
JavaScript Collections Hard 1 views
Like0

Write a JavaScript function that creates an object with a custom Symbol.iterator method that yields a sequence of numbers from start to end. The object should be iterable with for-of and spread operators.

Symbol.iterator is a well-known Symbol in JavaScript that defines the default iterator for an object. Any object with a [Symbol.iterator] method that returns an iterator object (with .next() method returning {value, done}) is iterable. Built-in types like Array, Map, Set, and String all have default iterators.

Making objects iterable enables them to work with for-of loops, spread operators (...), destructuring assignment, and Array.from(). This protocol-based iteration system is unique to JavaScript and provides a unified interface for consuming sequences of values from diverse data sources.

Time complexity is O(n) for consuming the full iteration, O(1) per .next() call. The iterator is lazy — values are computed only when .next() is called. Space complexity is O(1) for the iterator state.

Edge cases include empty ranges (iterator immediately returns {done:true}), single-element ranges, and ensuring the returned iterator object has the correct {value, done} format per the iteration protocol.

Example Input & Output

Example 1
Input
5,5
Output
[]
Explanation

Empty iteration

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

From 0 to 2

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

Negative to positive

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

Three elements

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

Iterate from 1 to 4

Algorithm Flow

Recommendation Algorithm Flow for Custom Iterator with Symbol

Solution Approach

Make a custom object iterable by implementing Symbol.iterator. Return an object with next() returning {value, done}.

function range(start, end) { return { [Symbol.iterator]: function() { var i = start; return { next: function() { return i <= end ? { value: i++, done: false } : { done: true } }; } }; } }

Custom iterables work with for...of, spread, destructuring. Generator functions simplify creation: function* range(s, e) { for (var i = s; i <= e; i++) yield i; }.

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

Best Answers

javascript - Approach 1
function solution(start, end) {
  var obj = {};
  obj[Symbol.iterator] = function() {
    var current = start;
    return {
      next: function() {
        if (current < end) {
          return { value: current++, done: false };
        }
        return { done: true };
      }
    };
  };
  return Array.from(obj);
}