JS Coding Question #2: Reverse a string

JS Coding Question #2: Reverse a string

Sep 06, 2021

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.

Code: https://codepen.io/angelo_jin/pen/LYyvBKy

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 like to watch a video instead.

https://youtu.be/VN7Yot7Zfns

Enjoy this post?

Buy letscode77 a coffee

More from letscode77