In programming, there is such a concept as
recursion - this is when a function
calls itself. Let's look at an example.
Using recursion, we derive numbers from
1
to 10
:
let i = 1;
function func(){
console.log(i);
i++;
if (i <= 10){
func(); // here the function calls itself
}
}
func();
Let's discuss how this code works.
We have the global variable i
and
the function func
, inside which
the contents of the variable i
are displayed to the console, and then
++
is performed.
If our variable i
is less than or
equal to 10
, then the function is
called again. Since the variable i
is global, then with each new call to the
function it will contain the value of the
variable i
specified
in the previous call.
It turns out that the function will
call itself until i
becomes
greater than 10
.
Please note that in our case it is
impossible to run the function without
if
- if you do this, you will
get an endless functions call.