JS⟩ syntax ⟩ for loops ⟩ for-of ⟩ with strings
String(s) are iterable.
let freq = {}; for(let char of "mississippi") { freq[char] = (freq ?. [char] ?? 0) + 1; } freq // { m: 1, i: 4, s: 4, p: 2 }
iterable
for-of with objects
for-in
arr.entries
related concepts used in examples
optional chaining (?., ?.[])
nullish coalescing (??)
replit: for-of with strings
Note:in the following code, '❤' is actually '❤️', except line 40, 46❗
// ⭐ string with emojis. const str = 'I ❤️ 🐣'; let count = 0; // count "characters" with for-of loop. let a = []; // store "characters" in an array. let i = 0; // array element index. // ⭐ collect "letters" using for-of for (a[i++] of str) { // ⭐ `lvalue` can be used in for-of. count += 1; } // ⭐ collect "letters" using `str.length` let b = []; for (let i = 0; i < 7; i++) { b[i] = str[i]; } // ⭐ code points // '❤️' has two code points❗ '❤️'.codePointAt(0), // 10084 '❤️'.codePointAt(1), // 65039 '🐣'.codePointAt(0), // 128035 // ⭐ string length is expected to be 5❗ // neither `.length` nor `for-of` is correnct❗ str.length, // 7❗ count, // 6❗ // (str.length) 7 elements❗ b.map(c => c.codePointAt(0)), // [73, 32, 10084, 65039, 32, 55357, 56355] // ╰─── ❤️ ───╯ ╰─── 🐣 ───╯ // └── surrogate pair ? // (for-of) 6 elements❗ a, // [ 'I', ' ', '❤', '️', ' ', '🐣' ] // ╰──❤️──╯ a.map(c => c.codePointAt(0)), // [ 73, 32, 10084, 65039, 32, 128035 ] // ╰─── ❤️ ───╯ ╰─🐣─╯ String.fromCodePoint(10084), // '❤'
JavaScript: The Definitive Guide ⟩ 5.4.4 for/of loop
Unicode Table ⟩ U+FE0F (65039)
for...of
Object ⟩
Object.keys()
Object.values()
Object.entries()
Object.prototype ⟩
.hasOwnProperty()
"in" operator
How to get the Unicode code point for a character in Javascript?
Why '❌'[0] === '❌' but '✔️'[0] !== '✔️'?
Last updated 2 years ago