Custom Iterator with Symbol
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
Empty iteration
From 0 to 2
Negative to positive
Three elements
Iterate from 1 to 4
Algorithm Flow

Solution Approach
Best Answers
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);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
