Example 1 — Loop a string
Each UTF-16 code unit is a value (emoji may be two).
JavaScript
for (const ch of "Hi") console.log(ch); How It Works
- Strings are iterable.
- Each character prints.
for...of loops the values of an iterable. Arrays, strings, Maps, Sets, and anything with Symbol.iterator work.
for (const color of ["red", "green"]) {
console.log(color);
} Each UTF-16 code unit is a value (emoji may be two).
for (const ch of "Hi") console.log(ch); Use entries() or keys().
for (const [i, v] of ["a", "b"].entries()) {
console.log(i + ":" + v);
} for...of on a Map yields [key, value] pairs.
const m = new Map([["x", 1]]);
for (const [k, v] of m) console.log(k, v); CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful