Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
The for...of loop iterates over values of iterable objects (arrays, strings, Maps, Sets, etc.). It's cleaner and more intuitive than traditional for loops!
const colors = ['red', 'green', 'blue'];
// Traditional for loop
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
// forEach (can't break/continue)
colors.forEach(color => {
console.log(color);
});const colors = ['red', 'green', 'blue'];
// for...of loop
for (const color of colors) {
console.log(color);
}
// Can use break/continue!Iterate over array values
const text = 'Hello';
// Using charAt()
for (let i = 0; i < text.length; i++) {
console.log(text.charAt(i));
}
// Or bracket notation
for (let i = 0; i < text.length; i++) {
console.log(text[i]);
}const text = 'Hello';
// for...of with strings
for (const char of text) {
console.log(char);
}
// H e l l oCharacter-by-character iteration
const arr = ['a', 'b', 'c'];
// for...of → VALUES
for (const value of arr) {
console.log(value);
}
// Output: a b c
// for...in → INDEXES/KEYS
for (const index in arr) {
console.log(index);
}
// Output: 0 1 2
// With objects
const obj = { x: 1, y: 2, z: 3 };
// for...in → KEYS (use with objects)
for (const key in obj) {
console.log(key, obj[key]);
}
// Output: x 1, y 2, z 3
// for...of doesn't work with plain objects
// for (const value of obj) {} // ERROR!Choosing the right loop
// Set
const uniqueNumbers = new Set([1, 2, 3, 2, 1]);
for (const num of uniqueNumbers) {
console.log(num);
}
// Output: 1 2 3
// Map
const userRoles = new Map([
['alice', 'admin'],
['bob', 'user']
]);
for (const [name, role] of userRoles) {
console.log(`${name}: ${role}`);
}
// Output: alice: admin, bob: user
// Map.entries()
for (const entry of userRoles.entries()) {
console.log(entry);
}
// Output: ['alice', 'admin'], ['bob', 'user']Maps, Sets, and more
Practical uses of for...of
Iterates over values of iterables
Use with: arrays, strings, Maps, Sets
Iterates over keys/indexes
Use with: plain objects
Unlike forEach(), you can break out of for...of loops early
Arrays, strings, Maps, Sets, NodeLists, TypedArrays, and more!