Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding product of an array using recursion in JavaScript
We are required to write a JavaScript function that takes in an array of numbers. Our function should do the following two things:
Make use of a recursive approach.
Calculate the product of all the elements in the array.
And finally, it should return the product.
For example, if the input array is:
const arr = [1, 3, 6, 0.2, 2, 5];
Then the output should be:
36
How Recursion Works
Recursion breaks down the problem into smaller subproblems. For array product calculation:
Base case: Empty array returns 1 (multiplicative identity)
Recursive case: First element × product of remaining elements
Example: Basic Recursive Approach
const arr = [1, 3, 6, 0.2, 2, 5];
const arrayProduct = ([front, ...end]) => {
if (front === undefined) {
return 1;
}
return front * arrayProduct(end);
};
console.log("Array:", arr);
console.log("Product:", arrayProduct(arr));
Array: [ 1, 3, 6, 0.2, 2, 5 ] Product: 36
Alternative Approach: Using Index
We can also implement recursion using array indices:
function productRecursive(arr, index = 0) {
// Base case: reached end of array
if (index >= arr.length) {
return 1;
}
// Recursive case: current element * product of rest
return arr[index] * productRecursive(arr, index + 1);
}
const numbers = [2, 4, 3, 5];
console.log("Array:", numbers);
console.log("Product:", productRecursive(numbers));
Array: [ 2, 4, 3, 5 ] Product: 120
Handling Edge Cases
const arrayProduct = (arr) => {
// Handle empty array
if (arr.length === 0) return 1;
// Handle single element
if (arr.length === 1) return arr[0];
// Recursive case
const [first, ...rest] = arr;
return first * arrayProduct(rest);
};
// Test different cases
console.log("Empty array:", arrayProduct([]));
console.log("Single element:", arrayProduct([7]));
console.log("Multiple elements:", arrayProduct([2, 3, 4]));
console.log("With zero:", arrayProduct([1, 0, 5]));
Empty array: 1 Single element: 7 Multiple elements: 24 With zero: 0
Comparison of Methods
| Method | Readability | Memory Usage | Performance |
|---|---|---|---|
| Destructuring approach | High | Creates new arrays | Slower for large arrays |
| Index-based approach | Medium | No new arrays | Faster for large arrays |
Conclusion
Recursion provides an elegant solution for array product calculation. The destructuring approach is more readable, while the index-based method is more memory-efficient for larger datasets.
