How to use Recursion In Javascript
We could define recursion formally in simple words, that is, a function calling itself again and again until it doesn’t have left with it anymore.
Example: This example shows the above-explained approach.
// Creating array
let arr = [4, 8, 7, 13, 12];
// Function to find the sum of the array using recursion
function sumArray(arr, index) {
if (index === arr.length) {
return 0;
}
return arr[index] + sumArray(arr, index + 1);
}
console.log("Sum is " + sumArray(arr, 0));
Output
Sum is 44
How to find the sum of all elements of a given array in JavaScript ?
Finding the sum of all elements in a given array in JavaScript involves iterating through the array and accumulating the values using a loop or array method like reduce(). This process yields the total sum of all array elements.
Below all the approaches are described with a proper example:
Table of Content
- Using for loop
- Using forEach() Method
- Using reduce() Method
- Using Recursion
- Using Lodash _.sum() Method
Contact Us