Let's use recursion to sequentially display the elements of the array. Let the array be initially passed to the function parameters:
func([1, 2, 3]);
For now, without recursion, using the
shift
method, we will display all the elements
of the array in turn:
function func(arr) {
console.log(arr.shift()); // shows 1
console.log(arr); // shows [2, 3] - array has shrunk
console.log(arr.shift()); // shows 2
console.log(arr); // shows [3] - array has shrunk
console.log(arr.shift()); // shows 3
console.log(arr); // shows [] - array is empty
}
func([1, 2, 3]);
As you can see, the shift
method cuts
and returns the first element of the array,
while the array itself is reduced by that element.
Let's now use recursion:
function func(arr) {
console.log(arr.shift(), arr);
if (arr.length != 0) {
func(arr);
}
}
func([1, 2, 3]);
In fact, of course, the easiest way is to loop through the elements of an array. The examples given so far simply demonstrate the work of recursion on simple examples (not real ones). More useful examples of using recursion are just more complex, we will analyze them a little later.
Given an array:
let arr = [1, 2, 3, 4, 5];
Print the elements of this array to the console using recursion.