## DEV Community

Let's Code

Posted on • Updated on

# JS Coding Question #2: Reverse a string [Common Question - 3 Solutions]

#### Interview Question #2:

Write a function that reverses a string❓🤔

If you need practice, try to solve this on your own. I have included 3 potential solutions below.

Note: There are many other potential solutions to this problem.

Feel free to bookmark 🔖 even if you don't need this for now. You may need to refresh/review down the road when it is time for you to look for a new role.

#### Solution #1: Array methods

• very simple solution that will utilize array methods to reverse the string.
``````function reverseString(str) {
return str.split("").reverse().join("");
}
``````

#### Solution #2: Array forEach

• will cycle through each characters and push it on the temp variable created one by one in reversed order.
``````function reverseString(str) {
let reversedString = ''

str.split('').forEach(char => {
reversedString = char + reversedString
})

return reversedString
}
``````

#### Solution #3: Array reduce

• slightly better than second solution above. Will use reduce and add the result to the empty string in reverse.
``````function reverseString(str) {
return str.split('')
.reduce((prev, curr) => curr + prev, '')
}
``````

Happy coding and good luck if you are interviewing!

If you want to support me - Buy Me A Coffee

In case you like a video instead of bunch of code 👍😊

Vinayak Phal • Edited

You can use stack concept to reverse the string.

``````function reverseString(str) {
let reverseStr = "";
let strStack = str.split('');
while(strStack.length){
reverseStr+=strStack.pop();
}
return reverseStr;
}
``````

One more simple solution using length and traversing backwards.

``````function reverseString(str) {
let reverseStr = "";
for (let i = str.length - 1; i >= 0; i--) {
reverseStr += str[i];
}
return reverseStr;
}
``````

Let's Code • Edited

definitely a good possibility in my opinion. I got asked to code it on my last job but it is not to extreme like accounting for unicode. It was something quick and straight to the point. I imagine myself to not continue the interview if interview would go to this extreme. LOL

I wrote an article about FIzz Buzz as well, should be in this series and I was shocked to find out he was asked about it on his recent interview.

Maybe junior level can be asked perhaps?

Let's Code • Edited