for...of Loop
Part of the Fundamentals section of Coddy's JavaScript journey — lesson 65 of 77.
The for...of loop provides a simple way to iterate over the values of iterable objects, such as arrays, strings, maps, sets, and more. It combines the conciseness of forEach with the ability to break and continue.
Here's the basic syntax of a for...of loop:
for (const element of iterable) {
// Code to be executed for each element
}element: On each iteration, the next value from the iterable object is assigned to this variable.iterable: The object whose elements are being iterated over (e.g., an array or a string).
Here's an example with an array:
const fruits = ["apple", "banana", "orange"];
for (const fruit of fruits) {
console.log(fruit);
}Output:
apple
banana
orangeHere's another example with a string:
const text = "hello";
for (const char of text) {
console.log(char);
}Output:
h
e
l
l
oCompared to traditional for loops or the forEach method, for...of offers a more straightforward syntax for many common use cases, especially when you don't need the index of each element.
Challenge
EasyWrite a function named countVowels that takes a string as an argument and returns the number of vowels (a, e, i, o, u) in the string. Use a for...of loop to iterate over the characters of the string.
For example:
countVowels("hello")should return 2countVowels("javascript")should return 3
Count also upper letters!
Cheat sheet
The for...of loop provides a simple way to iterate over the values of iterable objects like arrays and strings. It combines the conciseness of forEach with the ability to break and continue.
Basic syntax:
for (const element of iterable) {
// Code to be executed for each element
}Example with an array:
const fruits = ["apple", "banana", "orange"];
for (const fruit of fruits) {
console.log(fruit);
}Example with a string:
const text = "hello";
for (const char of text) {
console.log(char);
}Try it yourself
function countVowels(str) {
// Write code here
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Type Coercion7Bill Split Calculator
Welcome MessageCalculating The Tip And Total2Variables
NumbersStringBooleanNaming ConventionsEmpty VariablesRecap - Initialize VariablesConstants3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsStrict vs Loose EqualityRecap - Simple Math6Basic IO
OutputOutput with VariablesType Conversion - Part 1Type Conversion - Part 2Recap - Till 120Recap - True or False