or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

Lodash Sum

Lodash 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.

Package Information

  • Package Name: lodash.sum
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install lodash.sum

Core Imports

const sum = require('lodash.sum');

For ES modules environments (CommonJS package):

import sum from 'lodash.sum';

Basic Usage

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); // => 0

Capabilities

Array Summation

Computes 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:

  • Empty arrays: Returns 0
  • Falsy input: Any falsy value (null, undefined, false, 0, "", etc.) returns 0
  • Undefined array elements: Skipped during summation (not included in result)
  • Non-numeric values: Processed through JavaScript's automatic type coercion during addition
  • Type: Pure function with no side effects

Usage 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]); // => 0

Error Handling

The sum function is designed to be robust and does not throw errors under normal usage:

  • Any falsy input (null, undefined, false, 0, "", NaN) returns 0
  • Arrays containing undefined elements skip those elements during summation
  • Non-numeric array elements undergo JavaScript's automatic type coercion during addition
  • No input validation or type checking is performed - the function relies on JavaScript's truthy/falsy evaluation