Tilopa108
Tilopa108

Reputation: 41

noob javascript recursion

I'm a sys admin trying to learn javascript as a first language. One of the text I am studying has this code example in the chapter on recursion.

(variables changed for simplicity)

function fruit(n) {
    return n > 1 ? fruit(n - 1) + "apples" : "bananas";
}

I understand the ternary operator aspect of the function, the same thing could be written as this:

function fruit(n) {
    if n > 1
      return fruit(n - 1) + "apples";
    else
      return "bananas";
}

when I call the function I get the following result

console.log(fruit(3));

bananas apples apples

I don't understand how the first value is bananas (would that not mean the conditional 3 > 1 would be false)? What is going on in terms of how this code is executed to come up with that result?

Not sure if this site is noob friendly but thanks in advance for any help.

Upvotes: 1

Views: 200

Answers (5)

RAHUL MITTAL
RAHUL MITTAL

Reputation: 11

try to create a binary tree structure in a paper you will start to understand, Firstly 3 is given which will be true so it will return fruit(2)+"apple" continue this until you reach the else part and then start to go up in the binary tree and you will get the output, always try to think how a computer would process it

Upvotes: 0

Sahil Tayade
Sahil Tayade

Reputation: 19

If you trace your code, it will be clearer what is going on.

You can think of recursion as layers, and each call goes deeper and deeper in. When these calls resolve, they resolve in the reverse order, with the latest recursion resolving first, then coming outwards to the outward layer.

If you wanted to print the latest recursion at the end you should change

return fruit(n-1) + "apples"

to

return "apples"+ fruit(n-1)

Upvotes: 0

Andreas L.
Andreas L.

Reputation: 2923

I have tested your code like follows:

<script>
function fruit(n) {
    console.log("Called with " + n);
    if (n > 1) {
      return fruit(n - 1) + "apples ";
    } else {
      console.log("Called with " + n + " returning bananas.");
      return "bananas ";
    }
}
console.log(fruit(3));
</script>

My output:

Called with 3
Called with 2
Called with 1
Called with 1 returning bananas.
bananas apples apples 

The line return fruit(n - 1) + "apples "; means you concatenate a string: "bananas" + "apple" + "apple".

Looking on every step:

fruit(3):
- calling fruit(2)
- - calling fruit(1)
- - get return "bananas" // string consinst of "bananas" only here
- get return "apple" // string = "bananas" + "apple"
get return "apple" // string = "bananas" + "apple" + "apple"

EDIT: If you want to have bananas at the end. Change

return fruit(n - 1) + "apples ";

to

return "apples " + fruit(n - 1);

Upvotes: 1

leigero
leigero

Reputation: 3283

This happens because recursion continues as follows:

function fruit(n) {
if n > 1
  return fruit(n - 1) + "apples";
else
  return "bananas";
}

In the example you gave (listed above) you check to see if n > 1. In this case n = 3 so the answer is yes. So what do we do? We execute fruit(2).

Is 2 greater than 1? yes, so what do we do? We execute fruit(1).

Is 1 > 1? No, so we write Bananas.

Then recursion sort of back-tracks, writing the apples and apples as it returns to finish the previous methods.

VISUAL EXAMPLE: Since we know that the function will return "bananas" only when n <= 1

function fruit(3) will return SOMETHING and then write "apples"

  fruit(3) = fruit(2) apples
  fruit(2) = fruit(1) apples
  fruit(1) = banana

so you see, therefore substituting [fruit(2)] and (fruit(1)):

fruit(3) = [fruit(1) apples] apples
fruit(3) = [(banana) apples] apples

Upvotes: 0

Krease
Krease

Reputation: 16215

When figuring out recursion, it's best to start with the base case. In this case, your base case is fruit(1) - I hope it's clear that this returns bananas.

Now consider fruit(2) - this will return fruit(1) + "apples", and we already know fruit(1) is bananas, so this means bananas apples.

Extend this case further - fruit(3) is basically fruit(2) + "apples", and you already know what fruit(2) is... you end up with "bananas apples" + "apples", giving you your result.

Upvotes: 4

Related Questions