Recursion is a programming technique in which a function calls itself until certain conditions are met. Recursion in JavaScript can be used to solve problems involving repeating a task or breaking a problem into smaller subtasks.
For recursive functions, a new execution context is created each time the function is called, and the function is called again with the changed input values.
Syntax:
Output:
Eating a apple
Eating a banana
Eating a orange
Eating a kiwi
Eating a pear
No more fruits to eat!
In this example, the ‘eatFruit’ function takes an array of fruits as an argument and recursively eats each fruit in the array.
In the base case, there are no more fruits in the array, at which point the function outputs “No more fruits to it!” to the console.
Otherwise, the function removes the first fruit from the array using the ‘shift()’ method, prints a message saying that fruit is being eaten, and then calls itself with the modified fruit array.
This process continues until there are no fruits left in the array, at which point the base case starts and the recursion stops.