- JS Introduction
- JS Introduction
- JS Comments
- JS Variables
- JS Datatypes
- JS Operators
- JS Type Conversions
- JS Control Flow
- JS Comparisons
- JS If else
- JS If else Ladder
- JS Ternary Operator
- JS Switch
- JS For Loop
- JS For In
- JS For Of
- JS While
- JS Do While
- JS Break & Continue
- JS Functions
- JS Function Declaration
- JS Function Parameters
- JS Return Statement
- JS Function Expressions
- JS Anonymous Functions
- JS Objects
- JS Objects
- JS Object Methods
- JS Object Constructors
- JS Object Destructuring
- JS Object Prototypes
- JS Map, Filter & Reduce
- JS ES6
- JS ES6
- JS let and const
- JS Arrow Functions
- JS Template Literals
- Destructuring Assignment
- JS Spread Operator
- JS Default Parameters
- JS Classes
- JS Inheritance
- JS Map
- JS Set
- JS Async
- JS Callbacks
- JS Asynchronous
- JS Promises
- JS Async/Await
- JS HTML DOM/BOM
- JS Document Object
- JS getElementbyId
- getElementsByClassName
- JS getElementsByName
- getElementsByTagName
- JS innerHTML
- JS outerHTML
- JS Window Object
- JS History Object
- JS Navigator Object
- JS Screen Object
JavaScript for...of Loop
The for...of loop, introduced in ES6 (ECMAScript 2015), is a modern and highly readable way to iterate over data. Unlike older looping methods, it focuses directly on the values of an iterable object rather than their indices or keys. This makes your code more expressive and significantly reduces the boilerplate required to process collections.
Why it is Used:
- Readability: It provides a clean, declarative syntax that clearly communicates your intent: "for every item of this collection, do this."
- Value-Focused: It extracts the actual value directly, so you don't have to write
myArray[i]every time you want to access an element. - Broad Compatibility: It works out-of-the-box with Arrays, Strings, NodeLists (from the DOM), Maps, Sets, and even custom generators.
- Control Flow: Unlike the
.forEach()method,for...ofallows you to usebreak,continue, andreturnstatements, giving you full control over the loop's execution.
for...of when you need to use await inside a loop. It handles asynchronous operations sequentially, whereas forEach can lead to unexpected behavior with async/await.
Syntax:
for (const value of iterable) {
// Logic to process the value
}
- Variable: On each iteration, the current value is assigned to this variable. You can use
letorconst. - Iterable: Any object that has the "iterable protocol" (like an Array, Map, or String).
const in the loop head (e.g., for (const item of items)) if you aren't reassigning the variable within the loop block. This ensures the value remains immutable during that specific iteration.
Examples:
Iterating Over an Array:
This is the most common use case. It replaces the traditional for (let i = 0; i < arr.length; i++) approach.
const projects = ['Website Redesign', 'API Integration', 'Mobile App'];
for (const project of projects) {
console.log(`Current Project: ${project}`);
}
for...of on a standard Object. Objects are not iterable by default. If you try to loop over { name: 'John' }, you will get a TypeError. Use Object.keys() or Object.entries() instead.
Extracting Unique Characters from a String:
Strings are iterable in JavaScript, meaning for...of treats the string as a sequence of characters.
const sentence = 'code more';
let uniqueChars = new Set();
for (const char of sentence) {
if (char !== ' ') {
uniqueChars.add(char);
}
}
console.log('Unique Characters found:', [...uniqueChars].join(', '));
Iterating Over a Map:
When looping over a Map, each entry is returned as an array [key, value]. You can use array destructuring to make this very readable.
const userRoles = new Map([
['Alice', 'Admin'],
['Bob', 'Editor'],
['Charlie', 'Viewer']
]);
// Destructuring [key, value] directly in the loop
for (const [user, role] of userRoles) {
console.log(`${user} has the role of: ${role}`);
}
Filtering Even Numbers in an Array:
While .filter() is a great functional approach, for...of is excellent when you need to perform more complex logic or side effects while filtering.
const dataPoints = [12, 5, 8, 130, 44];
const evenResults = [];
for (const point of dataPoints) {
if (point % 2 === 0) {
console.log('Processing even point:', point);
evenResults.push(point);
}
}
for...of with for...in. for...in iterates over the property names (keys) of an object, whereas for...of iterates over the values of an iterable. Using for...in on an array will give you indices (0, 1, 2) as strings!
Summary
The for...of loop is the gold standard for iterating over collections in modern JavaScript. It removes the mental overhead of managing counters and array bounds, allowing you to focus on the actual data logic. Whether you are handling a list of DOM elements, processing a Set of unique IDs, or destructuring keys and values from a Map, for...of provides the most readable and flexible solution available.