- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array concat() method
- Array indexOf()
- Array length
- Array pop()
- Array shift
- Arrays
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Comment
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Date getTime()
- Destructuring
- Else
- Else if
- Enum
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- forEach()
- Function
- Function bind()
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- includes()
- Infinity property
- Iterator
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Object.keys()
- Overriding methods
- Parameters
- Promises
- Random
- Reduce
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- Sort
- Splice
- String
- String concat()
- String indexOf()
- Substring
- Switch statement
- Template literals
- Ternary operator
- Tile
- Type conversion
- While loop
JAVASCRIPT
JavaScript Iterator: Syntax, Usage, and Examples
A JavaScript iterator is an object that allows you to traverse through a collection one element at a time. It follows a specific protocol: each call to its next()
method returns an object with two properties—value
and done
. You can use iterators to loop over arrays, strings, maps, sets, or even custom objects. Learning how to work with an iterator JavaScript provides gives you more flexibility and control over data structures.
Whether you're building complex loops, handling streams of data, or customizing iteration behavior, understanding the iterator in JavaScript helps you write cleaner and more powerful code.
How to Use a JavaScript Iterator
An object becomes an iterator when it implements the iterator protocol. This means it has a next()
method that returns:
{
value: any,
done: boolean
}
value
: The current item.done
: A boolean that tells you whether the iteration is finished.
Built-in Iterators
Arrays, strings, sets, and maps have built-in iterators. You can access them with the [Symbol.iterator]
property:
const array = ["a", "b", "c"];
const iterator = array[Symbol.iterator]();
console.log(iterator.next()); // { value: "a", done: false }
console.log(iterator.next()); // { value: "b", done: false }
console.log(iterator.next()); // { value: "c", done: false }
console.log(iterator.next()); // { value: undefined, done: true }
When to Use iterator JavaScript Methods
Custom Iteration Behavior
You can build your own iterable objects with custom rules for iteration:
const customIterable = {
data: [10, 20, 30],
[Symbol.iterator]() {
let i = 0;
return {
next: () => {
return i < this.data.length
? { value: this.data[i++], done: false }
: { done: true };
}
};
}
};
for (let val of customIterable) {
console.log(val); // 10, 20, 30
}
Traversing Collections Without Loops
Sometimes you don’t want to use for...of
. Using the iterator directly gives you precise control:
const names = ["Alice", "Bob"];
const iter = names[Symbol.iterator]();
let result = iter.next();
while (!result.done) {
console.log(result.value);
result = iter.next();
}
Build Your Own Generator-Like Structure
Custom iterators can simulate generator behavior in older environments or special situations:
function range(start, end) {
return {
[Symbol.iterator]() {
let current = start;
return {
next() {
if (current <= end) {
return { value: current++, done: false };
}
return { done: true };
}
};
}
};
}
for (const num of range(1, 3)) {
console.log(num); // 1, 2, 3
}
Examples of JavaScript iterator in Action
Iterate Through a String
Strings have built-in iterators:
const str = "hi";
const iter = str[Symbol.iterator]();
console.log(iter.next()); // { value: "h", done: false }
console.log(iter.next()); // { value: "i", done: false }
console.log(iter.next()); // { value: undefined, done: true }
Convert a JavaScript Array to Iterator
Arrays can be converted into iterators using the same [Symbol.iterator]
property:
const nums = [1, 2, 3];
const iter = nums[Symbol.iterator]();
console.log(iter.next().value); // 1
console.log(iter.next().value); // 2
Use a Map Iterator in JavaScript
Maps also use iterators. You can get keys, values, or entries:
const map = new Map([
["name", "Eli"],
["age", 28]
]);
const keys = map.keys();
console.log(keys.next()); // { value: "name", done: false }
const values = map.values();
console.log(values.next()); // { value: "Eli", done: false }
This lets you build dynamic key-value iterations for configuration or user settings.
Iterate Through a Set
const set = new Set([1, 2, 3]);
const iter = set[Symbol.iterator]();
for (let result = iter.next(); !result.done; result = iter.next()) {
console.log(result.value); // 1, 2, 3
}
The iterator behaves just like it does with arrays.
Learn More About JavaScript Iterator
What Is the Iterator Protocol?
The iterator protocol defines how objects can be iterated. An object is considered iterable if it has a [Symbol.iterator]()
method that returns an object with a next()
method.
This approach ensures consistency across iterable structures like arrays, sets, maps, and custom types.
for...of
vs. Iterator
for...of
uses the iterator under the hood. The difference is that for...of
is simpler but less flexible.
const list = ["x", "y", "z"];
for (const item of list) {
console.log(item);
}
You can’t pause or resume for...of
, but you can control a manual iterator.
Chaining Iterators
You can combine multiple iterators into one:
function* combine(...iterables) {
for (const iterable of iterables) {
yield* iterable;
}
}
for (const val of combine([1, 2], ["a", "b"])) {
console.log(val); // 1, 2, a, b
}
This is useful in merging data sources.
Creating a JavaScript Map Iterator for Custom Objects
const user = {
name: "Sam",
age: 25
};
const keys = Object.keys(user);
const mapIterator = keys.map((key) => [key, user[key]])[Symbol.iterator]();
console.log(mapIterator.next()); // { value: ["name", "Sam"], done: false }
This helps when working with custom key-value pairs.
Using Generators Instead of Manual Iterators
In most modern code, you can use generators to simplify iterator creation:
function* gen() {
yield 1;
yield 2;
yield 3;
}
const iter = gen();
console.log(iter.next()); // { value: 1, done: false }
Generators simplify syntax and manage state automatically.
Handling Iteration with Breaks or Conditions
You can pause iteration when a condition is met:
const list = [10, 20, 30];
const iter = list[Symbol.iterator]();
let step = iter.next();
while (!step.done) {
if (step.value > 15) break;
console.log(step.value);
step = iter.next();
}
This gives you precise control over iteration flow.
A JavaScript iterator provides a structured way to step through elements in a collection, one at a time. It powers many of JavaScript’s modern features—from loops and generators to maps and sets.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.