Module 4: Control Flow – Conditionals and Loops
Loops: for...of and for...in
JavaScript provides other for
loop variations for iterating over collections.
1. for...of
loop (ES6+):
Iterates over the values of an iterable object (like Arrays, Strings, Maps, Sets, etc.).
let colors = ["red", "green", "blue"]; for (let color of colors) { console.log(color); } // Output: // red // green // blue let message = "Hi"; for (let char of message) { console.log(char); } // Output: // H // i
This is generally the preferred way to iterate over the values of an array.
2. for...in
loop:
Iterates over the enumerable properties (keys) of an object.
let person = { name: "Alice", age: 30, city: "New York" }; for (let key in person) { console.log(key + ": " + person[key]); } // Output (order might vary): // name: Alice // age: 30 // city: New York
Caution with for...in
for Arrays:
While you can use for...in
with arrays (since arrays are objects), it iterates over array indices (as strings) and also any other enumerable properties added to the array object. This can lead to unexpected behavior. For iterating over array elements, for...of
or a standard for
loop with an index is generally safer and more idiomatic.