for...of Loop
The for...of and for...in loops offer convenient ways to iterate over array elements and object properties in JavaScript. Both loops are used for iteration but apply to different scenarios.
for...of Loop
The for...of loop is designed for iterating over iterable objects (like arrays, strings, Set and Map objects). It makes it easy to loop through elements of a collection.
Syntax:
for (let variable of iterable) {
// code to be executed for each element
}
Example:
let array = [1, 2, 3, 4, 5];
for (let value of array) {
console.log(value);
}
// Output: 1 2 3 4 5
Using with Arrays
The for...of loop is handy for iterating over array elements, as it provides access to each element's value:
let fruits = ['apple', 'banana', 'cherry'];
for (let fruit of fruits) {
console.log(fruit);
}
// Output: apple banana cherry
Using with Strings
You can also use the for...of loop to iterate over characters in a string:
let str = 'Hello';
for (let char of str) {
console.log(char);
}
// Output: H e l l o
9.2 for...in Loop
The for...in loop is used to iterate over the enumerable properties of an object. It iterates over each property's key.
Syntax:
for (let key in object {
// code to be executed for each element
}
Example:
let obj = {a: 1, b: 2, c: 3};
for (let key in obj) {
console.log(key + ': ' + obj[key]);
}
// Output: a: 1 b: 2 c: 3
Using with Objects
The for...in loop is handy for iterating over object properties, providing access to each property's key and value:
let user = {
name: 'John',
age: 30,
isAdmin: true
};
for (let key in user) {
console.log(key + ': ' + user[key]);
}
// Output: name: John age: 30 isAdmin: true
Using with Arrays
The for...in loop can be used to iterate over array indices, but it's not recommended as it iterates over all enumerable properties, including prototype properties:
let array = ['apple', 'banana', 'cherry'];
for (let index in array) {
console.log(index + ': ' + array[index]);
}
// Output: 0: apple 1: banana 2: cherry
9.3 Comparing for...of and for...in Loops
Comparison of for...of and for...in loops:
| Description | for...of | for...in |
|---|---|---|
| Usage | Iterable objects (arrays, strings, Set, Map) | Objects |
| Features | Iterates over values | Iterates over keys |
| Using with arrays | for (let value of array) { ... } |
for (let index in array) { ... } |
| Using with objects | for (let value of Object.values(obj)) { ... } |
for (let key in obj) { ... } |
GO TO FULL VERSION