Hello! In our last lesson, we tackled the tricky subject of infinite loops, learning how to spot and prevent them by ensuring every loop has a valid exit condition. We highlighted how manual loops like for and while require careful management of counters and conditions.
Today, we'll introduce a much cleaner and safer way to handle iteration. This lesson focuses on the for...of loop, a modern JavaScript feature designed to iterate directly over the elements of data structures like arrays and strings. You'll learn how it simplifies your code, reduces the risk of common looping bugs, and works on any "iterable" data structure. We'll even take a look under the hood to understand the mechanism that makes it all possible.
The Modern Way to Loop: for...of
In previous lessons, to loop through an array, you'd write something like this:
const fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
This works, but it has moving parts you have to manage: initializing i, checking the condition i < fruits.length, and incrementing i. A mistake in any of these can lead to bugs, like the infinite loops we just discussed.
The for...of loop, introduced in ES6, simplifies this dramatically. Its purpose is to loop over the values in an iterable object.
Let's see how it works with arrays and strings.
#28 For...of loop | JavaScript Full Tutorial
This video from Dev Dreamer provides a clear, practical introduction to the for...of loop. It demonstrates the basic syntax and how to apply it to both arrays and strings, the two most common use cases you'll encounter.
Watch from the beginning to 03:17. Pay close attention to the loop's structure: for (let item of collection). Notice how the item variable directly holds the value of each element, not its index.
As you saw, the syntax is much more concise and readable:
// For an array
const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
console.log(fruit);
}
// For a string
const greeting = "Hello";
for (const char of greeting) {
console.log(char);
}
Notice the use of const for the variable fruit. Since for...of creates a new fruit variable for each iteration, you can use const if you don't plan on reassigning it inside the loop. This is a common and recommended practice.
The Critical Difference: for...of vs. for...in
JavaScript has another loop that looks similar: for...in. It's crucial to understand that they serve different purposes.
for...ofiterates over the values of an iterable (e.g., array elements, string characters).for...initerates over the keys (property names) of an object.
Using for...in on an array can lead to unexpected and incorrect behavior. Let's see why.
Introduction to JavaScript for...of Loop in ES6
This article from javascripttutorial.net provides a crystal-clear explanation of this difference with a code example that highlights why you should avoid for...in for arrays.
Please read the section titled "for...of vs. for...in". Focus on the code example that uses an array with an added .message property. Observe how for...in includes the property name ('message') in its output, while for...of correctly iterates only over the array's numeric values.
Here's a summary to keep in your notes:
| Feature | for...of |
for...in |
|---|---|---|
| Iterates over | The values of an iterable. | The keys/properties of an object. |
| Use Case | Arrays, Strings, Maps, Sets. | Plain objects. |
| Example | for (const element of ['a','b']) -> 'a', 'b' |
for (const key in {a:1, b:2}) -> 'a', 'b' |
| Array Behavior | Correct and Recommended. | Incorrect. Returns indices as strings and other properties. |
Under the Hood: The Iterator Protocol
You've expressed a strong interest in understanding why things work. The for...of loop is a perfect opportunity for a deep dive. It doesn't magically know how to go through an array; it works because of a built-in mechanism in JavaScript called the iterator protocol.
Here's the core idea:
- An object is considered iterable if it knows how to provide an iterator. It signals this by having a special method named
Symbol.iterator. - The
for...ofloop starts by calling thisSymbol.iteratormethod, which returns an iterator object. - This iterator object has a
next()method. - The
for...ofloop repeatedly callsnext(). Each time,next()returns an object with two properties:value: The next element in the sequence.done: A boolean that isfalseas long as there are more elements, andtruewhen the sequence is finished.
- The loop assigns the
valueto your loop variable and continues untildoneistrue.
This process is abstract, but seeing it done manually makes it click.
How To Use Iterators in JavaScript - Iterate Over Arrays and Collections
This video from dcode brilliantly visualizes the iterator protocol. It shows how you can manually 'drive' the iteration process, revealing exactly what for...of does for you automatically.
Watch from 01:39 to 07:06. The key part begins when the presenter manually gets the 'iterator' from the array and calls the .next() method on it. Observe the { value: ..., done: ... } object that is returned each time. This is the 'under the hood' secret of the for...of loop!
This iterator protocol is a fundamental concept in modern JavaScript. Data structures like Arrays, Strings, Maps, and Sets all come with a built-in Symbol.iterator, which is why for...of works on them out of the box.
Test your understanding!
A plain JavaScript object like const user = { name: 'Alex', age: 30 }; is not iterable by default. Based on what you just learned about the iterator protocol, why will a for...of loop fail on this user object?
Show answer
A for...of loop will fail on the user object because plain objects do not have a Symbol.iterator method. When the loop tries to call this method to get an iterator, it finds that the method doesn't exist, and JavaScript throws a TypeError: user is not iterable.
To iterate over the properties of a plain object, you should use the for...in loop.
Practical Usage: break, continue, and Getting the Index
The for...of loop works with the break and continue keywords, just like the loops we've already studied.
#28 For...of loop | JavaScript Full Tutorial
Let's see a quick example of how you can exit a for...of loop early using the break keyword.
Watch from 03:17 to 04:13. This demonstrates using an if statement inside the loop to check for a condition and break out prematurely.
But what if you need the element's index? While for...of focuses on values, you can get both the index and value by using the array's .entries() method combined with destructuring (which we will cover in-depth in a future module).
Introduction to JavaScript for...of Loop in ES6
This article shows a clean, modern pattern for getting both the index and the value during iteration.
Find the section "1) Iterating over arrays" and scroll to the part that discusses the entries() method. Look at the code example: for (const [index, color] of colors.entries()). This is a powerful pattern that gives you the best of both worlds.
Practice Exercises
Time to put this into practice. Open your code editor and solve the following problems.
Exercise 1: Summing Numbers
- Create an array of numbers, e.g.,
[10, 20, 30, 40, 50]. - Initialize a variable
totalto0. - Use a
for...ofloop to iterate through the array. In each iteration, add the number to thetotal. - After the loop, log the final
totalto the console. It should be150.
Show solution
const numbers = [10, 20, 30, 40, 50];
let total = 0;
for (const num of numbers) {
total += num; // Shorthand for total = total + num;
}
console.log(total); // Output: 150
Explanation: The for...of loop provides each number from the numbers array one by one. In each iteration, that number (num) is added to the running total.
Exercise 2: Building a String with a Condition
- Create an array of letters, e.g.,
['J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't']. - Initialize an empty string variable, e.g.,
let newWord = '';. - Use a
for...ofloop to iterate through the array. - Inside the loop, use an
ifstatement with thecontinuekeyword to skip any lowercase'a'characters. - For all other characters, append them to your
newWordstring. - After the loop, log
newWordto the console. It should be"JvScrpt".
Show solution
const letters = ['J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't'];
let newWord = '';
for (const letter of letters) {
if (letter === 'a') {
continue; // Skip the rest of this iteration and go to the next letter
}
newWord += letter; // Append the letter to the new word
}
console.log(newWord); // Output: "JvScrpt"
Explanation: The loop iterates over each letter. The if statement checks if the current letter is 'a'. If it is, continue is executed, which immediately ends the current iteration and starts the next one, effectively skipping the line newWord += letter. If the letter is not 'a', it gets appended to newWord.
Conclusion
You've now learned the modern and preferred way to iterate over collections in JavaScript. The for...of loop is not just syntactic sugar; it's a safer, more readable, and less error-prone alternative to traditional for loops, built on the powerful iterator protocol.
Key Takeaways:
- The
for...ofloop iterates directly over the values of iterable data structures like arrays and strings. - It simplifies iteration by removing the need to manage an index and exit condition manually.
- It is fundamentally different from
for...in, which iterates over the keys of an object and should not be used for arrays. - This all works because of the iterator protocol, where an object provides an iterator with a
next()method that thefor...ofloop uses to get each value until it's done.
Next Up:
We have now covered the two main pillars of control flow: conditionals (if/else, switch) and loops (for, while, for...of). With these tools, you can direct the flow of your program's execution. In our next lesson, we will dive into another fundamental building block of programming: functions. Functions allow us to organize our code into named, reusable blocks, making our programs more modular, readable, and powerful.