R
R
RichardXXX2019-01-04 22:34:21
recursion
RichardXXX, 2019-01-04 22:34:21

Explain the code with recursion?

Code given.

function myFunction(n){

        if(n==1){ return "1";}
        return myFunction(n - 1) + " " + n;

    };

    
    document.write(myFunction(10));

I understand a little about recursion, I did the factorial myself in 3 ways and Fibonacci.
But here I can not understand how the recursion works.
The code prints numbers from 1 to n , in ascending order, but I've already lost an hour and can't catch up why in ascending and not descending order.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2019-01-04
@RichardXXX

Think about this (an hour may not be enough):

function myFunction(n){
        if(n==1){ return "1";}
        return n + " " + myFunction(n - 1);

    };

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question