Spot the Bug - N_01
Published at 2025-01-10
Updated at 2025-01-10
Updated in 7 days
Licensed under MIT
spot-the-bug
challenge
Do you consider yourself a code detective? οΈβπ©π»βπ»ππ¨πΌβπ» We have a little mystery to solve. This JavaScript snippet seems to work perfectly, but hides a rather peculiar bug.
Can you figure out whatβs going on and why the result is not as expected?
Take the challenge and put your programming skills to the test!
function reverseString(str) {
return str.split("").reverse().join("");
}
const reversedString = reverseString("Hello, π!");
console.log(reversedString);
Remember, the satisfaction of solving a problem yourself is priceless. Try to research and solve it before you see the answer.
π Solution π©π»βπ»ππ¨πΌβπ»
This bug occurs because the split
method treats the string as an array of 16-bit units, not as an array of characters resulting the unexpected output: !οΏ½οΏ½ ,olleH
.
By using Array.from(str)
or [...str]
the string is split into an array of actual characters, respecting the surrogate pairs.
Using Array.from
:
function reverseString(str) {
return Array.from(str).reverse().join("");
}
const reversedString = reverseString("Hello, π!");
console.log(reversedString);
Using the spread operator:
function reverseString(str) {
return [...str].reverse().join("");
}
const reversedString = reverseString("Hello, π!");
console.log(reversedString);
I hope this has been helpful and/or taught you something new!