JavaScript Iterables & Generators — Interview Questions & Answers
Ques: What are Iterables in JavaScript?
Ans: An Iterable is any object that can be looped over using for...of, the spread operator (...), or destructuring.
Examples of iterables:
- Arrays
- Strings
- Maps
- Sets
- TypedArrays
- Generator objects
for (let char of "JS") console.log(char); // J S
Ques: What makes an object iterable?
Ans: An object becomes iterable when it implements the Symbol.iterator method, which returns an iterator.
const iterable = {
items: [10, 20, 30],
[Symbol.iterator]() {
let i = 0;
return {
next: () => ({
value: this.items[i++],
done: i > this.items.length
})
};
}
};
for (let val of iterable) console.log(val); // 10, 20, 30
Ques: What is an Iterator in JavaScript?
Ans: An Iterator is an object that provides a next() method returning { value, done }.
const arr = [1, 2];
const it = arr[Symbol.iterator]();
console.log(it.next()); // { value: 1, done: false }
console.log(it.next()); // { value: 2, done: false }
console.log(it.next()); // { value: undefined, done: true }
Ques: Difference between Iterable and Iterator
| Feature | Iterable | Iterator |
|---|---|---|
| Definition | Object implementing Symbol.iterator | Object returned by iterator function |
| Method | Has [Symbol.iterator]() | Has .next() |
| Usage | Used in for...of or spread syntax | Used for manual iteration |
| Example | Array, String, Map | arr[Symbol.iterator]() |
Ques: How does the for...of loop work internally?
Ans: It calls the object's [Symbol.iterator]() method and repeatedly calls .next() until { done: true }.
Ques: What is a Generator function in JavaScript?
Ans: A Generator is a special function that can pause and resume execution using the yield keyword.
It returns an iterator object.
function* generatorFunc() {
yield 1;
yield 2;
yield 3;
}
Ques: How do you call a generator function?
Ans: When called, it doesn’t execute immediately. Instead, it returns an iterator.
const gen = generatorFunc();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }
Ques: What is the purpose of the yield keyword?
Ans: yield pauses the generator function and returns a value to the caller.
Execution can be resumed later using .next().
Ques: Example: Simple Generator
function* countToThree() {
yield 1;
yield 2;
yield 3;
}
for (let num of countToThree()) {
console.log(num);
}
Output:
1
2
3
Ques: Can generators take input?
Ans: Yes, You can pass a value back into the generator via next(value).
function* greet() {
const name = yield "What is your name?";
yield `Hello, ${name}!`;
}
const g = greet();
console.log(g.next().value); // What is your name?
console.log(g.next("Alice").value); // Hello, Alice!
Ques: What does the return() method of a generator do?
Ans: It terminates the generator immediately.
function* example() {
yield 1;
yield 2;
}
const gen = example();
console.log(gen.return('Stopped')); // { value: 'Stopped', done: true }
Ques: What does the throw() method do in generators?
Ans: It throws an error inside the generator.
function* data() {
try {
yield 1;
yield 2;
} catch (e) {
console.log("Error:", e);
}
}
const g = data();
console.log(g.next());
g.throw("Something went wrong!");
Ques: Are generators iterable?
Ans: Yes, they automatically implement the iterable protocol via [Symbol.iterator]().
function* numbers() {
yield 1;
yield 2;
}
for (let num of numbers()) console.log(num);
Ques: What are real-world use cases of generators?
- Lazy evaluation (generate data when needed)
- Infinite sequences
- Asynchronous control flow
- Custom iteration logic
- Stream processing (like file or data streams)
Ques: Example: Infinite sequence using Generator
function* infiniteCounter() {
let i = 1;
while (true) yield i++;
}
const counter = infiniteCounter();
console.log(counter.next().value); // 1
console.log(counter.next().value); // 2
Ques: Can you use yield* in a generator?
Ans: Yes, The yield* expression delegates control to another iterable or generator.
function* inner() {
yield 1;
yield 2;
}
function* outer() {
yield* inner();
yield 3;
}
for (let val of outer()) console.log(val); // 1, 2, 3
Ques: Difference between Regular Functions and Generators
| Feature | Regular Function | Generator Function |
|---|---|---|
| Keyword | function | function* |
| Execution | Runs completely | Can pause & resume |
| Returns | Single value | Iterator object |
| Control | No control | Controlled via next() |
| Use case | Simple tasks | Complex sequences or async flow |
Ques: Can Generators be used for asynchronous programming?
Ans: Yes, especially before async/await, generators were used with libraries like co to manage async flow elegantly.
function* asyncExample() {
const result = yield fetchData();
console.log(result);
}
Ques: What is the difference between yield and return?
| Keyword | Purpose | Behavior |
|---|---|---|
yield | Pause and return intermediate value | Can resume |
return | End the generator | Cannot resume |
Ques: Example: Using Generators with Promises
function* fetchData() {
const user = yield fetch("<https://api.example.com/user>");
console.log(user);
}
Ques: Can a generator return multiple values at once?
Ans: No, It returns one value at a time with each yield. To generate multiple values, use multiple yield statements.
Ques: Are generator functions hoisted?
Ans: No, Like function expressions, generator declarations are not hoisted.
Ques: Example: Custom Iterable with Generator
const range = {
*[Symbol.iterator]() {
for (let i = 1; i <= 5; i++) yield i;
}
};
for (let num of range) console.log(num); // 1–5
Ques: Advantages of Iterables & Generators
- Efficient memory usage
- Easy to build infinite/lazy sequences
- Simplified async flow control
- More readable code than callbacks
