For...of Loops
👨💼 When you want to iterate over an array and just need each value (not the
index),
for...of provides clean, readable syntax.The syntax:
for (const item of array) {
// use item
}
For example:
const fruits = ['apple', 'banana', 'cherry']
for (const fruit of fruits) {
console.log(fruit)
}
// Logs: apple, banana, cherry
- Create an array
colorswith at least 4 colors - Use
for...ofto log each color - Create an array
numberswith values[10, 20, 30, 40, 50] - Use
for...ofto calculate and log the sum of all numbers - Use
for...ofto find and log the largest number
💰 You can also use
for...of with strings to iterate over characters:for (const char of 'hello') {
console.log(char) // h, e, l, l, o
}