One-liner to find the sum of an array of numbers in JavaScript

The following one-liner can be used to find the sum of an array of numbers in JavaScript:

const sumOfArray = arrayOfNumbers.reduce((a, b) => a + b, 0);

This line of code uses the reduce() method, which is a higher-order function that applies a function to each element in an array and reduces the array to a single value. In this case, the function being applied is a simple addition operation, specified using an arrow function that takes two parameters a and b, and returns their sum a + b. The second argument to reduce() is an initial value of 0, which is assigned to the first parameter a of the arrow function. The reduce() method then applies the arrow function to each element in the arrayOfNumbers array, accumulating the sum of the elements as it goes along.

The result of the reduce() method is assigned to the variable sumOfArray, which holds the final sum of the array of numbers.

Overall, this one-liner is a concise and efficient way to calculate the sum of an array of numbers in JavaScript, using the reduce() method and an arrow function. It avoids the need for a loop or a separate accumulator variable, and can be easily adapted to handle other types of operations on array elements.

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: