Difference between sum and product of an array in JavaScript

We are required to write a JavaScript function that takes in an array of Numbers as the only argument. The function should calculate the sum of all numbers in the array and the product of all numbers. Then the function should return the absolute difference between the sum and the product.

Example

Following is the code ?

const arr = [1, 4, 1, 2, 1, 6, 3];
const sumProductDifference = (arr = []) => {
    const creds = arr.reduce((acc, val) => {
        let { sum, product } = acc;
        sum += val;
        product *= val;
        return {
            sum, product
        };
    }, {
        sum: 0,
        product: 1
    });
    const { sum, product } = creds;
    return Math.abs(sum - product);
};
console.log(sumProductDifference(arr));

Output

Following is the output on console ?

126

How It Works

The function uses the reduce() method to calculate both sum and product in a single pass through the array:

  • Initialize sum to 0 and product to 1
  • For each array element, add it to sum and multiply it with product
  • Return the absolute difference using Math.abs()

Alternative Approach Using Separate Calculations

const arr = [1, 4, 1, 2, 1, 6, 3];

const sumProductDifference2 = (arr = []) => {
    const sum = arr.reduce((acc, val) => acc + val, 0);
    const product = arr.reduce((acc, val) => acc * val, 1);
    return Math.abs(sum - product);
};

console.log("Sum:", arr.reduce((acc, val) => acc + val, 0));
console.log("Product:", arr.reduce((acc, val) => acc * val, 1));
console.log("Difference:", sumProductDifference2(arr));
Sum: 18
Product: 144
Difference: 126

Comparison

Method Array Passes Readability Performance
Single reduce with object 1 Moderate Faster
Separate calculations 2 Higher Slower

Conclusion

The single reduce approach is more efficient as it calculates sum and product in one pass. Use Math.abs() to ensure the result is always positive regardless of which value is larger.

Updated on: 2026-03-15T23:19:00+05:30

261 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements