typedArray.fill(value, start, end) sets the elements from start up to, but not including, end to the same value. It changes the typed array in place and returns the same typed array, so calls can be chained. The value is converted to the element type first: a Uint8Array wraps it, a Uint8ClampedArray clamps it, and a Float32Array rounds it to single precision.
Remember
new Uint8Array(4).fill(7) → 7 7 7 7
ta.fill(0, 1, 3) → only indexes 1 and 2
ta.fill(5, -2) → the last two
Uint8Array.fill(300) → 44 (wraps)
Uint8ClampedArray.fill(300) → 255 (clamps)
returns the same typed array
Syntax
Only the value is required. The end index is not included.
Set only the elements at indexes 2, 3, and 4 to 0.
ta.fill(1).fill(9, 2)
Chain calls, because fill() returns the same typed array.
Available since ES2015 on all 11 types. A BigInt array needs a BigInt value such as 7n.
Library declarations
JavaScript
TypedArray.prototype.fill(value, start = 0, end = length)
// value is converted ONCE to the element type
// negative start/end count from the end
// returns the SAME typed array (this)
Parameters
Parameter
Description
value
The value to write. It is converted to the element type, so out-of-range numbers wrap (or clamp for Uint8ClampedArray).
start (optional)
Index of the first element to change. Negative counts from the end. Defaults to 0.
end (optional)
Index to stop before. Negative counts from the end. Defaults to the length.
Return Value
Return Value
Description
TypedArray
The same typed array you called it on (not a copy), now with the new values.
JavaScript Examples
Example 1 — Fill the Whole Array or a Range
A row of five pixels starts at 0. We paint all of them, then repaint a range, and check what fill() returns.
Bytes wrap around. In a Uint8Array 300 becomes 44 and -1 becomes 255, while an Int8Array turns 200 into -56.
Clamped bytes stop at the edges. A Uint8ClampedArray stores 255 for 300 and 0 for -5, and rounds halves to the nearest even number, so 1.5 and 2.5 both give 2.
Floats keep single precision. A Float32Array cannot store 0.1 exactly and prints its nearest single-precision neighbour.
Example 3 — Negative Indexes and Chained Calls
Negative start and end count from the end, and because the same array is returned, calls can follow each other. BigInt arrays need a BigInt value.