The for..of loop is for looping over objects that implement the Iterable
interface (expose a Symbol.iterator
property).
In this section we’ll demonstrate iterating over:
This the multi-page printable view of this section. Click here to print.
const str = "hello";
for (const s of str) {
console.log(s, typeof s);
}
h string
e string
l string
l string
o string
const nums = [2, 3, 4];
let sum = 0;
// Use `let i` because i mutates (`i++`).
for (let i = 0; i < nums.length; i++) {
sum += nums[i];
}
console.log(`sum: ${sum}`);
sum: 9
const set = new Set([2, 2, 3, 3, 4, 4]);
for (const val of set) {
console.log(val);
}
2
3
4
Iterate over map entries as key,value tuples.
const map = new Map([
["a", 1],
["b", 2],
["c", 3],
]);
for (const entry of map) {
console.log(entry);
}
[ "a", 1 ]
[ "b", 2 ]
[ "c", 3 ]
Iterate over the map, accessing the key and value parts as variables.
const map = new Map([["a", 1], ["b", 2], ["c", 3]]);
for (const [k, v] of map) {
console.log(`key: ${k} => value: ${v}`);
}
key: a => value: 1
key: b => value: 2
key: c => value: 3
Iterate over just keys.
const map = new Map([["a", 1], ["b", 2], ["c", 3]]);
for (const [key] of map) {
console.log(`key: ${key}`);
}
key: a
key: b
key: c
Iterate over just the values. Note that a placeholder is required for each key,
as designated by the underscore (_
).
const map = new Map([["a", 1], ["b", 2], ["c", 3]]);
for (const [_, value] of map) {
console.log(`value: ${value}`);
}
value: 1
value: 2
value: 3