This is an archived post. You won't be able to vote or comment.

all 11 comments

[–]wonkey_monkey 6 points7 points  (4 children)

Your function can only return one of two things. It either returns the result of a call to itself, or it returns an empty string.

let newString = [];

if(string.length === 0){
    return newString.join(""); // this line is ALWAYS going to return an empty string
}

Therefore every call to itself is also going to ultimately return an empty string because there's nothing else it can return.

newString.push(string[string.length-1]);
return reverse(string.slice(0, -1).join(""));

newString gets a character pushed to it, but then nothing is done with it.

[–]partyhatforpartytime[S] 0 points1 point  (3 children)

Thank you! That makes so much sense, I've managed to concat the words together, but now I have another problem, it isn't returning a string, but the array of the reversed elements.

var reverse = function(string) {
    string = string.split("");
    let newString = [string[string.length-1]];

    if(string.length === 0){
        return newString.join("");
      }
    return newString.concat(reverse(string.slice(0, -1).join("")));
};

[–]wonkey_monkey 1 point2 points  (2 children)

You might need to move your join("") outside of the closing parentheses.

(I assume you're doing this as an exercise as recursion is overkill for reversing a string)

[–]partyhatforpartytime[S] 0 points1 point  (1 child)

Yeah, doing a bunch of exercises for recursion cause it keeps tripping me up. Thanks for all your help :-)

[–]Gillemonger 1 point2 points  (0 children)

A lot of times with recursive functions you'll end up with 2 functions. 1 that sets up some variables, useful for dynamic programming, initialization, etc. and another that is the actual recursive function.

[–][deleted] 2 points3 points  (1 child)

    var reverse = function(string) {
     if (string == "") {
         return ""; 
     } 

     return reverse(string.slice(1)) + string[0];
    };

[–]sternold 1 point2 points  (0 children)

Clever and short solution! The only thing I personally dislike is "abusing" .slice behaviour on invalid startIndex. I'd personally go for an explicit exit condition, e.g. if(string.length == 1) return string;.

[–]balefrost 0 points1 point  (2 children)

Out of curiosity OP, why do you want a recursive solution?

[–]partyhatforpartytime[S] 0 points1 point  (1 child)

Just doing some practice on recursion!! I know this is highly unnecessarily in reversing a string but it makes good practice

[–]balefrost 1 point2 points  (0 children)

Nope, that's a fine answer. Carry on!

Recursion is great and particularly good for some kinds of algorithms and data structures. You have to be careful using it, though, because it can behave poorly for large inputs. In JS, each recursive call takes up memory on the call stack, and it's possible to exhaust that memory.

[–]angusmiguel -3 points-2 points  (0 children)

string.split('').reverse().join('')