for...of Loop

Imagine a bowl of gol gappe (pani puri) in front of you. 😋

You don't count "Puri number 0, puri number 1, puri number 2..." You just pick one puri, eat it, pick the next one, eat it, and keep going until the bowl is empty.

That is exactly how the for...of loop works. It picks each item one by one from a list, without caring about position numbers.

In the For Loop lesson, we went through an array like this:

We had to manage i, write the condition, use .length, and access fruits[i]. That is four things to take care of, and four chances to make mistakes.

With for...of, the same work becomes:

Clean, short, and easy to read! ✨

What Is a for...of Loop?

A for...of loop goes through each value of an iterable (like an array or string), one at a time, from start to end.

An iterable is anything that can be gone through one item at a time. In JavaScript, these include:

IterableExample
Array["Red", "Green", "Blue"]
String"Hello"
MapA list of key-value pairs
SetA list of unique values

Not iterable: plain objects like { name: "Ravi" }. We will see how to handle them later in this lesson.

Syntax

for (const item of iterable) {
  // use item
}
PartMeaning
itemA variable that holds one value in each round. You can name it anything.
ofThe keyword that means "go through the values of this list"
iterableThe array, string, Map, or Set you want to loop through

Your First for...of Loop

How It Works, Step by Step

RoundValue of color
1"Red"
2"Green"
3"Blue"
—No more values → loop stops

Key points:

  • Read it like English: "for each color of colors."
  • The loop stops automatically after the last item. No infinite loop worries!
  • There is no index to manage, so there are no off-by-one errors.

const or let?

Each round creates a fresh variable, so you can safely use const.

Use let only if you want to change the variable inside the loop:

Tip: Use const by default, just like with normal variables.

Part 1: for...of with Arrays

This is the most common use of for...of.

Example 1: Calculating a shopping bill 🛒

Example 2: Finding the highest score 🏏

Example 3: Counting passed students ✅

Example 4: Sending festival wishes 🪔

Part 2: for...of with Strings

for...of goes through a string one character at a time.

Example: Counting vowels

Example: Reversing a word

Bonus: It handles emojis correctly! 🎉

A normal for loop with an index can break emojis into strange symbols, but for...of reads them correctly. 👍

Part 3: Getting the Index with .entries()

for...of gives you only the value. What if you also need the position?

Use .entries(). It gives you the index and the value together.

How it works:

  • .entries() gives pairs like [0, "Ananya"], [1, "Rohan"], and so on.
  • [index, name] unpacks each pair into two variables. This is called destructuring, and you will learn more about it later.

Part 4: for...of with Map and Set

You will learn Map and Set in detail later, but here is a quick look, because for...of works perfectly with them.

Set: a list of unique values

Map: key-value pairs (like a better object)

Part 5: for...of with Objects (the Right Way)

Plain objects are not iterable, so for...of cannot loop through them directly.

✅ Fix: Convert the object into an array first, using these helper methods:

MethodGives you
Object.keys(obj)An array of keys
Object.values(obj)An array of values
Object.entries(obj)An array of key, value pairs

This is one of the most popular ways to loop through objects in modern JavaScript.


Using break and continue with for...of

Unlike forEach(), for...of fully supports break and continue. 👍

break: stop when found

continue: skip unwanted items


Can You Change Array Items with for...of?

This depends on what type of items the array has.

With primitive values (numbers, strings): ❌ No

The loop variable is only a copy. Changing it does not change the array.

Remember the photocopy example from the Data Types lesson? Writing on the photocopy doesn't change the original.

✅ Fix: Use .entries() to get the index, and update using it:

With objects: ✅ Yes, you can change their properties

Objects are shared (like a Google Doc), so changes do reach the original.


Looping Through an Array of Objects

This is very common in real projects, for example with data coming from a server.

Nested for...of Loops

You can put a for...of inside another one, for example for a 2D array (an array of arrays).

for...of vs Other Loops

Pointforfor...offor...inforEach()
Gives youIndexValueKeyValue + index
Works onAnything with an indexArrays, strings, Map, SetObjectsArrays only
break / continue✅✅✅❌
Index managementManualNot neededNot neededNot needed
Best forFull controlReading listsObject keysQuick array tasks

Simple way to choose:

  • Going through the values of a list? → for...of ✅
  • Going through the keys of an object? → for...in
  • Need to control the counter or jump steps? → normal for

Easy trick: of → values of a list. in → keys in an object.


Common Mistakes to Avoid

MistakeProblemFix
Using for...of on a plain object❌ TypeError: not iterableUse Object.entries() or for...in
Confusing of with in on arraysin gives string indexesUse of for array values
Changing the loop variable to update the arrayThe original array stays the sameUse .entries() with the index
Expecting the index automaticallyfor...of gives only valuesUse .entries()
Using it on null or undefined❌ TypeErrorCheck that the value exists first

Quick Summary Table

TaskCode
Loop through an arrayfor (const item of arr) { }
Loop through a stringfor (const char of str) { }
Get index + valuefor (const [i, v] of arr.entries()) { }
Loop through object valuesfor (const v of Object.values(obj)) { }
Loop through object key + valuefor (const [k, v] of Object.entries(obj)) { }
Loop through a Mapfor (const [k, v] of map) { }
Loop through a Setfor (const v of set) { }

Key Takeaways

  • The for...of loop goes through each value of an iterable, like arrays, strings, Maps, and Sets.
  • It is clean and safe: no index, no condition, no off-by-one errors, and it stops automatically.
  • Use .entries() when you need both the index and the value.
  • Plain objects are not iterable, so use Object.keys(), Object.values(), or Object.entries() with for...of.
  • It supports break and continue, which makes it more flexible than forEach().