• Make use of a recursive approach.

  • Calculate the product of all the">

    Finding product of an array using recursion in JavaScript



    We are required to write a JavaScript function that takes in an array of Integers. 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, .2, 2, 5];

    Then the output should be −

    const output = 36;

    Example

    The code for this will be −

    const arr = [1, 3, 6, .2, 2, 5];
    const arrayProduct = ([front, ...end]) => {
       if (front === undefined) {
          return 1;
       };
       return front * arrayProduct(end);
    };
    console.log(arrayProduct(arr));

    Output

    And the output in the console will be −

    36
    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements