TypedArray.prototype.subarray
Returns a new typed array on the same ArrayBuffer store and with the same element types as this typed array, from begin up to but not including end
Syntax
typedArray.subarray(begin?, end?)Parameters
| Parameter | Type | Description |
|---|---|---|
| begin | number | Element index to start at (inclusive) |
| end | number | Element index to end at (exclusive) |
Return Value
A new TypedArray sharing the same buffer
Examples
const arr = new Uint8Array([1, 2, 3, 4, 5])
const sub = arr.subarray(1, 4)
console.log(sub) // Uint8Array [2, 3, 4]const arr = new Float32Array([10, 20, 30, 40])
const sub = arr.subarray(2)
sub[0] = 99
console.log(arr[2]) // 99 (shared buffer!)function processChunks(data: Uint8Array, chunkSize: number) {
for (let i = 0; i < data.length; i += chunkSize) {
const chunk = data.subarray(i, i + chunkSize)
console.log('Chunk:', chunk)
}
}Understanding TypedArray.prototype.subarray
The TypedArray.prototype.subarray method in JavaScript returns a new typed array on the same ArrayBuffer store and with the same element types as this typed array, from begin up to but not including end. It belongs to the TypedArray object and is one of the most widely used methods for working with typedarray values in modern JavaScript and TypeScript applications.
The method signature is typedArray.subarray(begin?, end?). It accepts 2 parameters: begin, end. When called, it returns a new typedarray sharing the same buffer. Understanding when and how to use subarray() helps you write more expressive, readable code.
Common use cases for TypedArray.prototype.subarray include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like typedarray-slice, typedarray-set, arraybuffer-slice, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for TypedArray.prototype.subarray is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
TypedArray.prototype.sliceReturns a shallow copy of a portion of a typed array into a new typed array, with a new underlying ArrayBuffer
TypedArray.prototype.setStores multiple values in the typed array, reading input from a specified array or typed array
ArrayBuffer.prototype.sliceReturns a new ArrayBuffer whose contents are a copy of this ArrayBuffer's bytes from begin up to but not including end
More TypedArray Methods
Other methods in the TypedArray object
Related Tools
More TypedArray Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.