TypedArray.prototype.reduce() - JavaScript | MDN
Try it
const uint8 = new Uint8Array([0, 1, 2, 3]);
function sum(accumulator, currentValue) {
return accumulator + currentValue;
}
console.log(uint8.reduce(sum));
// Expected output: 6
Syntax
js
reduce(callbackFn)
reduce(callbackFn, initialValue)
Parameters
callbackFn-
A function to execute for each element in the typed array. Its return value becomes the value of the
accumulatorparameter on the next invocation ofcallbackFn. For the last invocation, the return value becomes the return value ofreduce(). The function is called with the following arguments:accumulator-
The value resulting from the previous call to
callbackFn. On the first call, its value isinitialValueif the latter is specified; otherwise its value isarray[0]. currentValue-
The value of the current element. On the first call, its value is
array[0]ifinitialValueis specified; otherwise its value isarray[1]. currentIndex-
The index position of
currentValuein the typed array. On the first call, its value is0ifinitialValueis specified, otherwise1. array-
The typed array
reduce()was called upon.
initialValueOptional-
A value to which
accumulatoris initialized the first time the callback is called. IfinitialValueis specified,callbackFnstarts executing with the first value in the typed array ascurrentValue. IfinitialValueis not specified,accumulatoris initialized to the first value in the typed array, andcallbackFnstarts executing with the second value in the typed array ascurrentValue. In this case, if the typed array is empty (so that there's no first value to return asaccumulator), an error is thrown.
Return value
The value that results from running the "reducer" callback function to completion over the entire typed array.
Exceptions
TypeError-
Thrown if the typed array contains no elements and
initialValueis not provided.
Description
See Array.prototype.reduce() for more details. This method is not generic and can only be called on typed array instances.
Examples
Sum up all values within an array
js
const total = new Uint8Array([0, 1, 2, 3]).reduce((a, b) => a + b);
// total === 6
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-%typedarray%.prototype.reduce |