Reversing a string is perhaps one of the most common interview questions one of those which inevitably we, as Software Developers, encounter during our journeys.
Let’s briefly recap how this approach actually works.
split()method splits our String object, so that every single character in the original String array is now separated in its own single-character substring.
reverse()method comes then into play and does the main job: it simply reverses the elements contained in the originally array so that what originally was the last character in the -String array, is now the first element (in our case it’s a “.” , since it’s the character that our variable “stringToReverse” was ending on).
join()method finally rejoins all the single characters previously separated by the
split()method to form and recompose our reversed string.
Et voilà! 😏
- Quick side note : This approach should preferably be used if your interviewer specifically says that you are allowed to use built-in methods, otherwise you should go for the next approaches I am going to show you.
If you wanna show your interviewer that you know how to solve this problem without relying on the JS built-in methods, just use the for loop.
But let’s just get a bit fancier and use the ES6 syntax, shall we?
for loop syntax introduced by ES6 is very handy and it drastically reduces the chance of making mistakes while typing code for the loop.
Also, it is much cleaner and nicer to look at 👌 .
With ES6 we have a new way of splitting our String into an array, thanks to the so-called spread operator
This approach is almost identical to the first approach I showed (except for the
[…] operator of course 😅 ) and here below you can have a look at it.
Pretty neat, huh? 😎
Passing the “stringToReverse” as a parameter of the spread operator allows us to “spread” the single character values contained in our original array to get the same result as we did using the
split() function, so that we can later reverse the all the single characters one by one as we did before with the JS built-in method
reverse() and then finish off once more with the
The last method I would like to show you is the recursive approach to this problem.
In this case we want to set up our function so that it recursively calls itself till it hits our base case (i.e. an empty string).
We simply cut the first character of our string object away with the
substr() method, and add it at the end of the string recursively till there are no more characters left to add.
We can even do this with a ternary operator to be more concise and clean with our JS syntax.
I truly hope you enjoyed this tutorial and please let me know your thoughts and solutions too!