reduce Accumulates With An Initial Value

reduce folds an array into one accumulator; the initial value guards empty arrays — without it an empty input throws, with it the seed returns.

JavascriptData Integrity

Code

javascriptsnippet
25 lines
// reduce 把数组折叠成单个累加值:initialValue 是第二参数
const latencies = [42, 18, 133, 7];
const total = latencies.reduce((sum, ms) => sum + ms, 0);
console.log('total:', total);

// 累积成对象:计数与求和同时进行
const stats = latencies.reduce(
  (acc, ms) => {
    acc.count += 1;
    acc.sum += ms;
    return acc;
  },
  { count: 0, sum: 0 },
);
console.log('count:', stats.count, 'sum:', stats.sum);

// 空数组没有初值会直接抛错
try {
  [].reduce((sum, n) => sum + n);
} catch (error) {
  console.log('empty array:', error instanceof Error ? error.message : String(error));
}

// 给了初值则正常返回初值本身
console.log('safe empty:', [].reduce((sum, n) => sum + n, 0));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

total: 200
count: 4 sum: 200
empty array: Reduce of empty array with no initial value
safe empty: 0

Inside the snippet

Top-level bindings latencies, total, stats hold the demo state — nothing sits inside a function scope.

Putting it to use

The demo output is labeled (total:, count:, empty array:), so every printed line maps back to its originating operation.

Core lines

const total = latencies.reduce((sum, ms) => sum + ms, 0);
[].reduce((sum, n) => sum + n);
acc.count += 1;

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. Its state lives in module-level bindings: `latencies`, `total`, `stats`.