What does this code log?
const str = 'a\uD83D\uDE00b';
console.log(str.length, [...str].length);
- 4 4
- 4 3
- 3 3
- 5 4
0
voters
What does this code log?
const str = 'a\uD83D\uDE00b';
console.log(str.length, [...str].length);
Going with “4 3” because str. length counts UTF-16 code units (4), while the spread operator correctly iterates over code points (3).
The emoji is a surrogate pair, so. length sees two code units for it, but spread groups the pair into one thing.
JS Quiz answer: Option 2 (B).
Correct choice: 4 3
Why:
The emoji is a surrogate pair (two UTF-16 code units), so str.length counts ‘a’, high surrogate, low surrogate, ‘b’ = 4. Spreading the string iterates by Unicode code points, treating the surrogate pair as one character, giving ‘a’, emoji, ‘b’ = 3.
Go deeper:
First-answer leaderboard
:: Copyright KIRUPA 2024 //--