Noob javascript recursion

I am a sys admin trying to learn javascript as the first language. One of the texts I'm learning 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 could be written like 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 a banana (does this mean that the conditional 3> 1 will be false)? What happens in terms of how this code is executed to come up with this result?

Not sure if this site is friendly, but well in advance for any help.

+4
source share
3 answers

. fruit(1) - , , bananas.

fruit(2) - fruit(1) + "apples", , fruit(1) is bananas, bananas apples.

- fruit(3) fruit(2) + "apples", , fruit(2) ... "bananas apples" + "apples", .

+4

:

<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>

:

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

(n - 1) + ""; , : "" + "" + "".

:

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: .

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

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

, :

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

, ( ), , n > 1. n = 3, . ? (2).

2 1? , ? (1).

1 > 1? , .

, , , .

: , "" , n <= 1

function fruit(3) SOMETHING, ""

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

, [fruit(2)] (fruit(1)):

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

Source: https://habr.com/ru/post/1526471/


All Articles