Among the functions, recursive functions can be distinguished separately. Their essence is that the function calls itself.
For example, consider a function that determines the factorial of a number:
function getFactorial(n){ if (n === 1){ return 1; } else{ return n * getFactorial(n - 1); } } var result = getFactorial(4); console log(result); // 24
The function getFactorial() returns the value 1 if the parameter n is equal to 1, or returns the result of the getFactorial function again, then the value n-1 is passed to it. For example, when passing the number 4, we have the following chain of calls:
var result = 4 * getFactorial(3); var result = 4 * 3 * getFactorial(2); var result = 4 * 3 * 2 * getFactorial(1); var result = 4 * 3 * 2 * 1; // 24
Consider another example – the definition of Fibonacci numbers:
function getFibonachi(n) { if (n === 0){ return 0; } if (n === 1){ return 1; } else{ return getFibonachi(n - 1) + getFibonachi(n - 2); } } var result = getFibonachi(8); //21 console log(result); // 21