Search code examples
javascriptrecursion

Recursive string reversal function in javascript?


I'm a pretty experienced frontend engineer with a weak CS background. I'm trying to get my head around the concept of recursion. Most of the examples and purported explanations I can find just aren't explaining it in a way I find easy to understand.

I set myself a task of writing a function that will reverse a string recursively. I know there has to be a base condition (i.e. the solution is found), but I can't figure out how to actually write something like this and could use a demo to study.

Could someone provide a sample function?


Solution

  • Something like:

    function reverse (str) {
        if (str === "") {
            return "";
        } else {
            return reverse(str.substr(1)) + str.charAt(0);
        }
    }
    

    So the function is recursive as it calls itself to do the work.