How to use for...of loop in JavaScript
The for…of loop provides a clean, readable way to iterate over iterable objects like arrays, strings, Maps, and Sets in JavaScript. As the creator of CoreUI with over 25 years of JavaScript development experience, I’ve used for…of loops extensively for data processing, UI rendering, and collection manipulation. From my expertise, the most effective approach is using for…of when you need to iterate over values rather than indices, providing cleaner syntax than traditional for loops. This ES6 feature simplifies iteration code while working seamlessly with modern JavaScript features like destructuring and async/await.
Use the for…of loop to iterate over values in iterable objects like arrays, strings, and collections.
const fruits = ['apple', 'banana', 'orange']
for (const fruit of fruits) {
console.log(fruit)
}
const message = 'Hello'
for (const char of message) {
console.log(char)
}
Here for (const fruit of fruits) iterates directly over array values, eliminating the need for index management. The loop works with any iterable object, including arrays, strings, Maps, Sets, and NodeLists. Each iteration provides the actual value, not the index, making the code more readable and less error-prone. Use const in the loop declaration since each iteration creates a new binding.
Best Practice Note:
This is the same approach we use in CoreUI components for rendering lists, processing configuration arrays, and iterating over DOM collections efficiently. Use for…of when you need values, for…in when you need object properties, and traditional for loops when you need precise index control or performance optimization.



