1

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.

Matt Greer
62.1k18 gold badges127 silver badges124 bronze badges
asked Feb 12, 2014 at 4:43
1
  • The first conditional calls fruit again. Run through the code on paper. Commented Feb 12, 2014 at 4:45

5 Answers 5

4

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.

answered Feb 12, 2014 at 4:48
Sign up to request clarification or add additional context in comments.

1 Comment

that is a great way to explain it.
1

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);
answered Feb 12, 2014 at 8:45

Comments

0

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
answered Feb 12, 2014 at 4:48

Comments

0

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)
answered Dec 31, 2021 at 20:41

Comments

0

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

answered Aug 3, 2022 at 18:51

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.