The lodash method sum exported as a module for computing the sum of values in an array.
npx @tessl/cli install tessl/npm-lodash-sum@4.0.0Lodash Sum provides the _.sum method exported as a standalone Node.js module. It computes the sum of all values in an array with robust handling of edge cases like empty arrays and undefined values.
npm install lodash.sumconst sum = require('lodash.sum');For ES modules environments (CommonJS package):
import sum from 'lodash.sum';const sum = require('lodash.sum');
// Basic array summation
const result = sum([4, 2, 8, 6]);
console.log(result); // => 20
// Handle empty arrays
const empty = sum([]);
console.log(empty); // => 0
// Handle null/undefined input
const nullResult = sum(null);
console.log(nullResult); // => 0Computes the sum of all values in an array, handling edge cases gracefully.
/**
* Computes the sum of the values in `array`.
*
* @static
* @memberOf _
* @since 3.4.0
* @category Math
* @param {Array} array The array to iterate over.
* @returns {number} Returns the sum.
* @example
*
* _.sum([4, 2, 8, 6]);
* // => 20
*/
function sum(array);Behavior Details:
00Usage Examples:
const sum = require('lodash.sum');
// Numeric arrays
sum([1, 2, 3, 4, 5]); // => 15
sum([10.5, 20.25, 5.75]); // => 36.5
// Arrays with mixed types (numeric coercion applies)
sum([1, '2', 3]); // => 6
sum(['10', '20', '30']); // => 60
// Edge cases
sum([]); // => 0
sum([undefined, 1, 2]); // => 3 (undefined elements are skipped)
sum([1, , 3]); // => 4 (sparse array holes become undefined, are skipped)
sum(null); // => 0
sum(undefined); // => 0
sum(false); // => 0
sum(0); // => 0
// Single value arrays
sum([42]); // => 42
sum([0]); // => 0
sum([-5, 5]); // => 0The sum function is designed to be robust and does not throw errors under normal usage:
0