The for...of
loop appeared to solve the problem of complex loops over arrays and strings. It gives you a way to access each value without a counter.
Table of Content
In this article, you will learn how the forā¦of loop works in JavaScript with examples.
Understand the for...of
Loop
The for...of
loop is a JavaScript statement that goes through the values of an iterable object one by one. It works with:
- arrays
- strings
- maps
- sets
- other objects
That are following the iterable protocol.
Here is the syntax:
for (const item of iterable) {
// code to run for each item
}
for
starts the loop.(const item of iterable)
:const
declares a new variable for each value.item
holds the current value in the loop.iterable
is the object with values to loop over, like an array or string.
{ ... }
: This block holds the code that runs each time through the loop.
Use it when:
- You want values, not keys or indexes.
- You loop through arrays, strings, maps, or sets.
- You do not need to change the original iterable.
- You want simpler, more readable loops.
You can use for...of
with any object that follows the iterable protocol. Here are the main ones:
- Arrays like
['a', 'b', 'c']
- Strings like
'hello'
- Maps loops through key-value pairs
- Sets loops through unique values
- Typed Arrays like
Uint8Array
- Arguments object inside a function
- DOM collections like
NodeList
Letās move on to the following part to understand how forā¦of works in JavaScript
How for...of
Works
The for...of
loop pulls values one at a time from an iterable. It starts at the first value and moves forward until it reaches the end.
Here is a deeper look at how the for...of
loop works behind the scenes:
- The object must be iterable
The loop only works if the object has a built-in method calledSymbol.iterator
. This method returns an iteratorāan object with anext()
method. - The iterator controls the loop
When the loop starts, JavaScript callsiterable[Symbol.iterator]()
. This returns the iterator. - The
next()
method returns values
Each time through the loop, JavaScript callsnext()
on the iterator. Thenext()
method returns an object with two properties:value
: the next value in the sequencedone
: a Boolean that istrue
when the sequence ends
- The loop stores each value in a variable
The loop assigns thevalue
from thenext()
result to the variable you wrote in the loop, likeconst item
. - The loop runs until
done
is true
As long asdone
isfalse
, the loop keeps going. Whendone
becomestrue
, the loop stops.
Here is an example with a custom iterable:
const myIterable = {
*[Symbol.iterator]() {
yield 10;
yield 20;
yield 30;
}
};
for (const num of myIterable) {
console.log(num);
}
The output:
10
20
30
This shows how JavaScript uses the Symbol.iterator
method and yield
to provide values. The for...of
loop uses these behind the scenes. You do not see the next()
calls, but they happen during each loop step.
Variable Patterns and Limits
The variable you declare inside the loop can follow a few patterns. But it also has limits. Here is how that works:
You can use a constant or let variable to store each value.
for (const value of [1, 2, 3]) {
console.log(value);
}
You cannot use var
in strict mode. It is better to use const
if you do not plan to change the value.
You can pull values apart when you loop through arrays of arrays or maps.
for (const [key, val] of Object.entries({a: 1, b: 2})) {
console.log(key, val);
}
This pattern works with arrays that return pairs or nested values:
a 1
b 2
Also, you do not get the index by default. If you need the index, use Array.entries()
:
for (const [index, value] of ['a', 'b', 'c'].entries()) {
console.log(index, value);
}
Output:
0 a
1 b
2 c
Plain objects ({}
) do not work with for...of
because they are not iterable. Use Object.keys()
or Object.entries()
if you want to loop through object data.
const obj = { x: 1, y: 2 };
for (const [key, value] of Object.entries(obj)) {
console.log(key, value);
}
Output:
x 1
y 2
If you use const
, you cannot reassign the loop variable inside the block. But you can still use or update its contents if it holds an object or array.
How to Use for...of
in JavaScript
You will see how for...of
works with arrays, objects, strings, and other types. Each part includes a full example to show what happens in detail.
Arrays
Arrays work well with for...of
because they are iterable. You get each value in order.
const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
console.log(fruit);
}
Output:
apple
banana
cherry
What happens:
- First loop:
fruit
is'apple'
- Second loop:
fruit
is'banana'
- Third loop:
fruit
is'cherry'
You do not need to use an index.
Objects
Regular objects are not iterable, so for...of
does not work on them directly. You must first convert the object to something iterable, like its keys or values.
const user = {
name: 'Tom',
age: 25,
city: 'Cape Town'
};
// Loop over values
for (const value of Object.values(user)) {
console.log(value);
}
// Loop over keys
for (const key of Object.keys(user)) {
console.log(key);
}
// Loop over key-value pairs
for (const [key, value] of Object.entries(user)) {
console.log(`${key}: ${value}`);
}
Output:
Tom
25
Cape Town
name
age
city
name: Tom
age: 25
city: Cape Town
What happens:
Object.values(user)
returns['Tom', 25, 'Cape Town']
Object.keys(user)
returns['name', 'age', 'city']
Object.entries(user)
returns[ ['name', 'Tom'], ['age', 25], ['city', 'Cape Town'] ]
Arguments Object
Inside a function, arguments
acts like an array, but it is not a real array. Still, you can use for...of
because it is iterable.
function showArgs() {
for (const arg of arguments) {
console.log(arg);
}
}
showArgs('one', 'two', 'three');
What happens:
- The loop prints:
one
two
three
Each argument becomes a value in the loop.
Strings
Strings are iterable. You get one character at a time.
const word = 'hello';
for (const char of word) {
console.log(char);
}
The loop prints:
h
e
l
l
o
Typed Arrays
Typed arrays, like Uint8Array
or Float32Array
, store numbers in a fixed format. They are iterable like normal arrays.
const scores = new Uint8Array([10, 20, 30]);
for (const score of scores) {
console.log(score);
}
What happens:
- The loop prints:
10
20
30
You use for...of
the same way you would with a regular array.
Maps
A Map
holds key-value pairs. It remembers the order. You can loop over it directly.
const map = new Map();
map.set('name', 'Alice');
map.set('age', 30);
for (const [key, value] of map) {
console.log(`${key}: ${value}`);
}
What happens:
- First loop:
key = 'name'
,value = 'Alice'
- Second loop:
key = 'age'
,value = 30
You can also use map.keys()
, map.values()
, or map.entries()
with for...of
.
Sets
A Set
holds only unique values. You can loop over it to get each one.
const colors = new Set(['red', 'green', 'blue']);
for (const color of colors) {
console.log(color);
}
What happens:
- The loop prints:
red
green
blue
No duplicates. If you add 'red'
again, the set keeps only one.
NodeList
A NodeList
comes from the DOM, like when you use document.querySelectorAll()
. It is iterable in modern browsers.
const items = document.querySelectorAll('li');
for (const item of items) {
console.log(item.textContent);
}
What happens:
Each item
is a DOM node. The loop prints the text from each list item.
Custom Iterables
You can build your own object that works with for...of
. You must use a method called [Symbol.iterator]
.
const range = {
start: 1,
end: 3,
[Symbol.iterator]() {
let current = this.start;
const end = this.end;
return {
next() {
if (current <= end) {
return { value: current++, done: false };
} else {
return { done: true };
}
}
};
}
};
for (const num of range) {
console.log(num);
}
What happens:
- First loop:
num = 1
- Second loop:
num = 2
- Third loop:
num = 3
- Then it stops because
done = true
You can create any custom logic inside your iterator. It must return an object with value
and done
.
Letās move on to the below section to take a look at the difference between for...of
and forā¦in
in JavaScript.
The Difference Between for...of
and for...in
The for...of
and for...in
loops may look similar, but they do very different things. If you pick the wrong one, your code may not work the way you want.
for...of
loops through values in an iterable.
That includes:
- arrays
- strings
- maps
- sets
- typed arrays
- NodeLists
- custom iterables
It ignores object keys and only gives you actual values in order.
const arr = ['a', 'b', 'c'];
for (const value of arr) {
console.log(value);
}
Output:
a
b
c
for...in
loops through keys (or property names) in an object.
It works on:
- regular objects
- arrays (but you usually should not use it there)
- anything with keys or properties
const obj = { name: 'Tom', age: 30 };
for (const key in obj) {
console.log(key); // name, age
console.log(obj[key]); // Tom, 30
}
Output:
name
Tom
age
30
Here is a table that shows you the key differences:
Feature | for...of | for...in |
---|---|---|
Loops over | Values in iterables | Keys in objects |
Works on | Arrays, Strings, Sets, Maps, etc. | Objects and Arrays (keys only) |
Output | Value at each step | Key or property name |
Use with arrays | Yes, safe and accurate | No, may loop unexpected keys |
Use with objects | No, unless converted to iterable | Yes, made for objects |
Example with Array:
const colors = ['red', 'green', 'blue'];
for (const color of colors) {
console.log(color); // red, green, blue
}
for (const index in colors) {
console.log(index); // 0, 1, 2
console.log(colors[index]); // red, green, blue
}
Output:
red
green
blue
0
red
1
green
2
blue
In for...of
:
You get each color directly.
In for...in
:
You get the index as a string and then use it to access the color.
Example with object:
const user = { name: 'Lila', city: 'Durban' };
for (const key in user) {
console.log(`${key}: ${user[key]}`);
}
Output:
name: Lila
city: Durban
Do not use for...of
here unless you convert it:
for (const [key, value] of Object.entries(user)) {
console.log(`${key}: ${value}`);
}
It prints the same result.
So, when to use what
Use for...of
when:
- You want values from an iterable.
- You are working with arrays, strings, sets, or maps.
Use for...in
when:
- You want property names from an object.
- You need to see custom or inherited keys.
Support in Browsers and Runtimes ( ECMAScript Specification)
The for...of
loop became part of JavaScript in ECMAScript 2015 (ES6). That means it works in most modern browsers and runtimes.
But if you want to target older environments or understand which engines support it, here is a clear breakdown.
for...of
is defined in the ECMAScript 2015 (ES6) specification.- It uses the iterator protocol, which allows you to loop through iterable values like arrays, strings, maps, sets, and more.
- The loop calls the
[Symbol.iterator]()
method on the target, then calls.next()
untildone
istrue
.
If a value does not follow the iterator protocol, you will get a TypeError
.
Browser Support:
All major browsers support for...of
, but support started at different versions:
Browser | Minimum Version that Supports for...of |
---|---|
Chrome | 38 |
Firefox | 13 (basic), full support by 36 |
Safari | 7.1 (basic), full support by 9 |
Edge (Legacy) | 12 |
Edge (Chromium) | All versions |
Internet Explorer | Not supported |
Opera | 25 |
Node.js Support
Node.js uses the V8 engine from Chrome, so support depends on V8 version.
Node.js Version | Support for for...of |
---|---|
0.12 | Partial (behind flag) |
4.x and above | Full support |
Safe to use in Node.js 4.0 or higher.
If you want to use for...of
in older environments (like IE), you can use Babel to transpile the code into something more compatible. Babel converts the loop into a standard for
loop that works with iterables.
Wrapping Up
You learned how the for...of
loop works in JavaScript. You saw how it gives you values directly from arrays, strings, maps, sets, typed arrays, and more. Also understood how it works behind the scenes with the iterator protocol.
You also learned the key difference between for...of
and for...in
. One gives you values from iterables. The other gives you keys from objects.
Here is a quick recap:
- Use the
for...of
loop to iterate over values in arrays, strings, maps, sets, and other iterable objects. - It uses
[Symbol.iterator]()
and.next()
to get values. - It works only with iterable objects.
- Use
for...in
when you need keys from plain objects. - Most modern browsers and Node.js versions support
for...of
. Internet Explorer does not. - For older browsers, you can use Babel to convert
for...of
into a regular loop.
What is the for...of loop in JavaScript?
What is the difference between the for...of loop and the for...in loop?
Can I use the for...of loop with non-iterable objects?
How can I get the index of elements while using the for...of loop?
const letters = ['a', 'b', 'c'];
for (const [index, value] of letters.entries()) {
console.log(index, value);
}
// Output:
// 0 'a'
// 1 'b'
// 2 'c'