0

I heard recursive function is powerful so instead going through loop i tried to create a function which increments a number until it reach certain points. when it reaches i tried to return the value, but it give undefined.

CODE

var i=1;
function rec(){
    i++;
    console.log(i);
    if(i > 100){
        return i;
    }else{
        rec();
    }
}

console.log(rec());

Here the i is incrementing until 100. but it returns undefined after the limit. Why is this happening? Also please let me know, it this kind of recursion is good then for loop?

4
  • 7
    else { return rec(); } ? Commented Nov 23, 2014 at 12:05
  • no. after it become > 100 i need to return. until i will call the function to increment the number. Just to practice recursion. Commented Nov 23, 2014 at 12:06
  • 1
    @rram: Yes, vaultah is right. Why don't you just try it? And step through the code with a debugger? Commented Nov 23, 2014 at 12:08
  • Dang! Now I know what it feels like.. Commented Aug 19, 2020 at 10:16

4 Answers 4

3

The comment by vaultah is correct:

let i = 1;
function rec() {
    i++;
    console.log(i);
    if (i > 100) {
        return i;
    } else {
        return rec();
    }
}

console.log(rec());


Let's take an example that only counts to > 5 and add some output so you can see what happens more easily (but again, stepping through the code with a debugger is the right way to see how this works):

let nesting = 0;
let i = 1;
function rec() {
    let rv;
    ++i;
    ++nesting;
    if (i > 5) {
        log(`${i} > 5, returning ${i}`);
        rv = i;
    } else {
        log(`${i} is not > 5, calling rec`);
        rv = rec();
        log(`Got ${rv} back from rec, returning it`);
    }
    --nesting;
    return rv;
}

log("Final result: " + rec());

function log(msg) {
    console.log(" ".repeat(nesting) + msg);
}


Sign up to request clarification or add additional context in comments.

10 Comments

Thanks for you guide. +1. Please check my latest fiddle.i got the idea of recursion. but why it didn't stop when i become 101 and just return 101. Instead it is returning undefined.
@rram: Because again the call that you're printing the result of doesn't return anything. If you step through the code, it'll become obvious why the above is how you do this.
What do you mean by step through code? Right now i am seeing the logs in firebug console. Here is the one more updated fiddle. Please check my comment too
@rram: A debugger can let you stop your code and then execute each line one at a time, looking at variables and such while you'er doing it. That's called "stepping through the code in a debugger." Meanwhile, see the second snippet above.
Sorry now more confused. Why are we getting Got 6 back from rec, returning it 4 times in the else part
|
1

rec will either return i (if i is over 100) or undefined (otherwise).

When you call it here:

console.log(rec());

i will be 1 so it will return undefined.

You never do anything with the return value when the return value is over 100.

You need to return the result of the recursive call:

} else {
    return rec();
}

so when it is over 100, the value gets passed back up the stack.

it this kind of recursion is good then for loop?

No. It is horribly inefficient.

3 Comments

Thanks for the help in explaining, but i couldn't understand a bit. Here is my doubt. I'm trying to increment the i variable until it becomes > 100. that is 101. so if that satisfies then i'm returning the i so the function stops. So no more recursion happen. The idea of return is to stop the recursion. instead why it is giving undefined at last? Here is the fiddle of modified code Please advice
@rram: Again, step through the code in a debugger (there's one built into your browser). The first call to rec will increment i and then check it. Since 2 is not > 100, we go to the else. In the else, we do return rec() which calls rec. This second call to rec increments i again, sees that 3 is not > 100, and calls rec again. This is the point of a recursive algorithm. Eventually, the 99th call to rec sees i > 100 and returns i, which allows the 98th call to return (and it returns the same value), which allows the 97th call to return, and so on.
Thanks for your answer with explanation of whether this is better than for loop. +1
0

Well you could just use the return statement and you can check the code in the console like

var i=1;
function rec(){
i++;
console.log(i);
if(i > 100){
    return i;
}else{
    return rec();
}
}

console.log(rec());

Comments

-2

Try putting the following code after your function ends:

typeof rec === 'undefined'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.