What are the ways to reverse a string in JavaScript?
There are three common ways to reverse a string in JavaScript, and they differ in how they treat characters that live outside the basic multilingual plane.
The most direct way is to split the string into an array, reverse the array, and join it back together. The reverse() method reverses an array in place, so you have to turn the string into an array first. Splitting on an empty string gives you an array of code units, and that is where the emoji problem comes from. Spreading the string instead gives you an array of whole characters, so that is the version you should prefer.
const word = 'Tutorsbot';
// Split into characters, reverse, and join back together.
console.log(word.split('').reverse().join(''));
// Spread first, so whole characters are used.
console.log([...word].reverse().join(''));
// Build the answer one character at a time.
let manual = '';
for (let index = word.length - 1; index >= 0; index--) {
manual = manual + word[index];
}
console.log(manual);
The second way is a manual loop that builds the result one character at a time, either with the charAt() method or by indexing the string. It takes more code and it is slower, but it works and it is easy to read when you want to be completely explicit about what is happening.
The third way is the reverse() method on the array prototype applied to the result of a split, which is really the first way written in a different shape.
Two things are worth knowing about the methods underneath. The array reverse() method changes the array it was called on, so reversing the result of a split is safe, because the split produced a brand new array. The string reverse() method does not exist at all, so any answer that claims otherwise is wrong.
In an interview, the version to reach for is the spread one, and the reason to give is that it handles characters outside the basic plane correctly. If you know that the input is plain ASCII text, then the split-on-empty-string version is fine and it is a little more familiar to most people.