Working with recursion in JavaScript

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.

Example with a parameter

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.

Sum of array elements

Let's now not display the array elements to the console, but find their sum:

function getSum(arr) { let sum = arr.shift(); if (arr.length !== 0) { sum += getSum(arr); } return sum; } console.log(getSum([1, 2, 3]));

Given an array:

let arr = [1, 2, 3, 4, 5];

Use recursion to find the sum of the squares of this array elements.