How to use Array reduce() Method In JavaScript

The Javascript Array reduce() method is used to reduce the array to a single value and executes a provided function for each value of the array (from left to right) and the return value of the function is stored in an accumulator.

Syntax:

arrayName.reduce(()=>{});

Example: The below code uses a JavaScript function with the Array reduce() method to iterate through numbers and return a string message if the sum is negative.

Javascript




function sumChecker(numbers) {
    const sum = numbers.reduce((acc, num) => acc + num, 0);
    if (sum < 0) {
        return `The sum of the numbers is ${sum}, and is negative.`;
    } else {
        return `The sum of the numbers is ${sum}, and is positive.`;
    }
}
 
console.log(sumChecker([1, -2, 3, -4, -5]));
console.log(sumChecker([1, 4, 5, -3, 2]));


Output

The sum of the numbers is -7, and is negative.
The sum of the numbers is 9, and is positive.


How to Iterate Through Numbers and Return a String Message if the Sum is Negative?

In JavaScript, iterating through numbers or any kind of iterable data structures is a common programming task. The ability to repeat a certain block of code multiple times allows you to perform operations on a set of data. We can iterate through an array of numbers and return a string message if the sum of the numbers is negative.

Table of Content

  • Using JavaScript For Loop
  • Using JavaScript For Of Loop
  • Using JavaScript While Loop
  • Using JavaScript Array forEach() Method
  • Using JavaScript Array reduce() Method

Similar Reads

Using JavaScript For Loop

The for loop in JavaScript is a control flow statement that allows you to repeatedly execute a block of code based on a specified condition. The for loop has three parts: initialization of a counter variable, the condition itself, and the update section....

Using JavaScript For Of Loop

...

Using JavaScript While Loop

The for of loop in JavaScript provides a concise and easy-to-read syntax for iterating through the values of an iterable, eliminating the need for explicit index management. This loop has namely two parts: the variable which is assigned the value of each element of the iterable on each iteration, and the iterable itself....

Using JavaScript Array forEach() Method

...

Using JavaScript Array reduce() Method

The while loop in JavaScript is a control flow statement that allows you to repeatedly execute a block of code as long as a specified condition evaluates to true....