πŸ‘¨πŸΌβ€πŸ’»

khriztianmoreno's Blog

Home Tags About |

Spot the Bug - N_01

Published at 2025-01-10
Updated at 2025-01-10
Licensed under MIT spot-the-bugchallenge

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!

Profile

@khriztianmoreno πŸš€