This will be a short one
In ES6 strings are by default iterable with a for/of loop character-by-character. When iterating over strings, they are iterated by the Unicode codepoint, not by UTF-16 characters.
This can leave room for unexpected behavior. Let's look at this string for example: "I🧡😀".
let str = "I🧡😀";
console.log(str.length); // => 5
for (let char of str) {
console.log(char); // => "I", "🧡", "😀"
}
This string has a .length
of 5 because the two emojis require each two UTF-16 characters to represent. But when you iterate over them with a for/of
loop, the loop body will run three times, once for each codepoint "I", "🧡", "😀".
Top comments (0)