Reversing a string
Realised-Prophets
Posted on November 17, 2022
I'm currently working through freeCodeCamp's 300h javascript course. One of the algorithm challenges is to reverse a string. I solved this with a for
loop, unshift()
and join()
like this:
function reverseString(str) {
let arr = [];
for (let i = 0; i < str.length; i++) {
arr.unshift(str[i]);
}
return arr.join("");
}
reverseString("Hello")
I declared an empty array to store the separate characters.
I wrote your usual FOR loop to iterate through the input string characters.
I used the unshift method because this pushes each new letter to the front, starting with H into my empty
arr
variable. It iterates though it like this:
[ 'H' ]
[ 'e', 'H' ]
[ 'l', 'e', 'H' ]
[ 'l', 'l', 'e', 'H' ]
[ 'o', 'l', 'l', 'e', 'H' ]
so by the end of the loop you end up with this array of letters which are in the reverse order.
4 . Now I have an array with the desired order, however, the challenge wants a single string. A quick google search provided me with the .join()
method, which I then use on my arr
variable. The result is olleH
When I finished I looked up a few other ways of doing this. I'll post them another day!
Love, RP
Posted on November 17, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.