By the end of this lesson, you will know how to use for...of, break, and continue in JavaScript to control loops effectively. Learning these key concepts will enhance your ability to manipulate and interact with data structures.
The for...of loop is useful for iterating over iterable objects like arrays, strings, or collections. It allows you to access each element directly without using an index. This makes your code cleaner and easier to read. For example, if you have a list of fruits, you can use the loop to display them easily:
File: fruits.php
const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
console.log(fruit);
}
apple
banana
cherry
The line for (const fruit of fruits) starts the loop. The variable fruit takes the value of each element in the array as the loop goes through it. Every iteration prints the fruit’s name using console.log(fruit). You can also use break to exit the loop if needed. Therefore, if a certain fruit—like a ‘Valencia orange’—is detected, you can stop the loop.
The break statement ends a loop early, while continue allows you to skip to the next iteration. For instance, you might want to skip over a specific fruit, like “banana” in the following example:
for (const fruit of fruits) {
if (fruit === 'banana') {
continue; // Skip banana
}
console.log(fruit);
}
apple
cherry
Create an array with at least five animals. Then, use a for...of loop to print each animal’s name. If the animal is “lion”, apply break to stop the loop. Practice using loop control statements together to understand their interplay.
const animals = ['dog', 'cat', 'lion', 'tiger', 'elephant'];
for (const animal of animals) {
if (animal === 'lion') {
break; // Stop loop
}
console.log(animal);
}
for...of is for values, not indices. If you need the index, use forEach or a traditional for loop instead.{}.for...of loop helps iterate over iterable objects, making your code easier to manage.break to exit loops early and continue to skip to the next iteration.Further reading: developer.mozilla.org · w3schools.com