Code Logo

Custom Iterator with Symbol

Published at25 Jul 2026
JavaScript Collections Hard 0 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
Recommendation Algorithm Flow for Custom Iterator with Symbol

Solution Approach

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);
}

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);
}