Reverse a String - JavaScript Solution & Walkthrough
(02/16) Learn how to solve coding challenges using FreeCodeCamp's curriculum.
02/16 Reverse a String
Reverse the provided string.
You may need to turn the string into an array before you can reverse it.
Your result must be a string.
function reverseString(str) {
return str;
}
reverseString("hello");
Credit: FreeCodeCamp.org
Understanding the Challenge
In this challenge, you are given a string. your task here is to create a function that returns the reversed version of the string.
For instance, if given a string of "hello" like in the example above, your reverseString()
function should return "olleh".
Don't forget the hint you've been given. "You may need to turn the string into an array before you can reverse it."
Now, you know what the challenge expects from you. Let's get into some pseudocode before we proceed.
Pseudocode
Given a string,
split the string into an array of the letters that forms the string
reverse the array of letters you now have.
join the letters so they are no longer an array but a string
return the string
Solving the Challenge
Okay, going by our pseudocode above, we first have to split the string. Splitting it will help us get an array of the letters (or characters) that forms the given string.
In the example str
is given as 'hello'
let finalString = str.split('');
console.log(strArray) // ['h', 'e', 'l', 'l', 'o']
In this case, applying .split('')
on str
gives us an array of the characters that makes up the given string "hello". Note that we passed an empty string as argument to .split('')
. This is what is enabling us to get the characters individually. If we had called .split()
without the empty string, we would have gotten this instead [ 'hello' ]
We can go ahead and reverse the array we have by calling .reverse()
on finalString
finalString.reverse()
console.log(finalString) // ['o', 'l', 'l', 'e', 'h']
We now have a reversed version of the characters of the given string. But it is still an array. We need to convert this into a string. We can do so using .join('')
.
finalString.join('')
console.log(finalString) // 'olleh'
Note: just like we called .split('')
with and empty string, we also need to call .join('')
with an empty string passed to it. This is what helps us get the string without any separator.
Final Solution
function reverseString(str) {
let finalString = str.split('').reverse().join('')
return finalString;
}
reverseString("hello"); // "olleh"
Congratulations!
You just cracked the second challenge in this series.
Cheers and happy coding!