Mastering JavaScript | For Of Loop
Welcome back to our "Master JavaScript" course! let's understand another useful loop in JavaScript: the for...of loop.
Before we proceed, make sure you've watched the for, for…in, while, do…while loop videos in the channel and subscribe that means a lot. Let's dive into the for...of loop with an example:
1
2
3
4
const carBrands = ["Toyota", "Honda", "Ford", "BMW", "Mercedes"];
for (const brand of carBrands) {
console.log(brand); // Output: Toyota, Honda, Ford, BMW, Mercedes
}
In this example, we have an array of carBrands
. The for...of loop allows us to iterate over each element in the array and store it in the brand
variable. We can then access and process each element inside the loop. For example, we print each car brand to the console, which displays all the car brands stored in the array.
Let's see another example to further understand the for...of loop:
1
2
3
4
const fruits = ["apple", "banana", "orange", "grapes"];
for (const fruit of fruits) {
console.log(fruit); // Output: apple, banana, orange, grapes
}
In this new example, we have an array of fruits
. the for...of loop allows us to loop through each fruit and access it using the fruit
variable. We can perform any desired operations on each element inside the loop such as printing the fruit element.
that was everything for today, If you're new to our channel, I highly recommend checking out our "Master JavaScript" video playlist. Thank you for watching, and see you in the next video! Happy coding!