JavaScript - For...of Loop

Welcome, aspiring programmers! Today, we're going to dive into one of JavaScript's most useful features: the for...of loop. As your friendly neighborhood computer science teacher, I'm excited to guide you through this journey. So, grab your favorite beverage, get comfortable, and let's embark on this coding adventure together!

Javascript - For...of

What is the for...of Loop?

Before we jump into the nitty-gritty, let's understand what the for...of loop is all about. Imagine you have a basket full of colorful fruits, and you want to examine each fruit one by one. The for...of loop is like your helpful assistant that picks up each fruit from the basket and hands it to you, one at a time, until the basket is empty.

In programming terms, the for...of loop allows us to iterate (fancy word for "go through") over iterable objects like arrays, strings, and other data structures that we'll learn about later.

Syntax

Now, let's look at how we write a for...of loop. Don't worry if it looks a bit strange at first – we'll break it down together!

for (variable of iterable) {
    // code to be executed
}

Let's dissect this:

  • for: This keyword tells JavaScript that we're starting a loop.
  • variable: This is where we'll store each item as we go through the iterable.
  • of: This keyword is what makes this a for...of loop.
  • iterable: This is the object we're looping through (like our fruit basket).
  • The code inside the curly braces {} is what we want to do with each item.

Examples

Example 1: Looping through an Array

Let's start with a simple example. We'll create an array of fruits and print each one.

let fruits = ['apple', 'banana', 'cherry', 'date'];

for (let fruit of fruits) {
    console.log(fruit);
}

If you run this code, you'll see:

apple
banana
cherry
date

What's happening here? Our for...of loop is taking each fruit from the fruits array and storing it in the fruit variable. Then, we're using console.log() to print each fruit.

Example 2: Looping through a String

Did you know that strings are iterable too? Let's spell out a word:

let word = 'Hello';

for (let letter of word) {
    console.log(letter);
}

This will output:

H
e
l
l
o

Each character in the string is treated as an individual item that we can loop through. Cool, right?

Example 3: Using for...of with Numbers

Now, let's get a bit more practical. Imagine you're a teacher (like me!) and you want to calculate the average score for a class:

let scores = [85, 92, 78, 95, 88];
let total = 0;
let count = 0;

for (let score of scores) {
    total += score;
    count++;
}

let average = total / count;
console.log(`The class average is ${average}`);

This script will calculate and print the average score. We're using the for...of loop to add up all the scores and count how many there are.

Example 4: Breaking out of a Loop

Sometimes, you might want to stop the loop before it finishes. We can do this with the break keyword. Let's say we're looking for a specific fruit:

let fruits = ['apple', 'banana', 'cherry', 'date'];
let searchFor = 'cherry';

for (let fruit of fruits) {
    if (fruit === searchFor) {
        console.log(`Found ${searchFor}!`);
        break;
    }
    console.log(`Checking ${fruit}...`);
}

This script will stop as soon as it finds 'cherry', without checking the remaining fruits.

Example 5: Skipping Items with continue

What if we want to skip certain items? We can use the continue keyword. Let's print only fruits that start with 'a':

let fruits = ['apple', 'banana', 'apricot', 'cherry', 'avocado'];

for (let fruit of fruits) {
    if (!fruit.startsWith('a')) {
        continue;
    }
    console.log(fruit);
}

This will only print 'apple', 'apricot', and 'avocado'.

Methods Table

Here's a handy table of methods we've used in our examples:

Method Description Example
console.log() Prints output to the console console.log('Hello, World!')
startsWith() Checks if a string starts with specified characters 'apple'.startsWith('a') // true
break Exits a loop if (condition) break;
continue Skips to the next iteration of a loop if (condition) continue;

Conclusion

And there you have it, folks! We've journeyed through the land of for...of loops, from simple arrays to strings, and even learned how to break out or skip items. Remember, practice makes perfect, so don't be afraid to experiment with these concepts.

In my years of teaching, I've found that the best way to learn is by doing. So, here's a little homework for you: Try creating your own for...of loops with different types of data. Maybe loop through your favorite movies, or the names of your friends. The possibilities are endless!

Happy coding, and remember – in the world of programming, every loop is an opportunity for discovery!

Credits: Image by storyset