Sub topic 7
Typed Array Methods: subarray, slice, set, and from
Typed arrays have most of the methods you know from regular arrays, but some of them behave differently, and a few are missing completely. For performance and correctness, the most important question about any method is whether it shares memory with the original buffer or copies the bytes into a new one.
This chapter assumes you already know how to create typed arrays over an ArrayBuffer, how byteOffset and length place a view inside a buffer, and how out-of-range values wrap or clamp. It also assumes you are comfortable with regular Array methods such as map, filter, and sort.
Views Versus Copies
Every typed array has a buffer property that points to the memory it reads and writes. Some methods create a new typed array over the same buffer. Others allocate a new buffer and copy bytes into it. The two results can look identical when you print them, but they behave differently as soon as you write to them.
subarray: a new window on the same bytes
subarray(begin, end) returns a typed array of the same type that covers elements begin up to, but not including, end. No bytes are copied. The new view's byteOffset is the parent's byteOffset plus begin * BYTES_PER_ELEMENT.
const buf = new ArrayBuffer(16);
const words = new Uint32Array(buf); // 4 elements
const middle = words.subarray(1, 3); // elements 1 and 2
console.log(middle.length); // 2
console.log(middle.byteOffset); // 4
console.log(middle.buffer === buf); // true
middle[0] = 42;
console.log(words[1]); // 42Negative indices count from the end, and indices outside the array are clamped rather than throwing. So words.subarray(-2) gives the last two elements, and words.subarray(2, 100) also gives elements 2 and 3.
The begin and end arguments count elements, not bytes. If you have a byte position and need a view at that position, construct a new typed array with new Uint8Array(view.buffer, view.byteOffset + n, len) instead.
slice: an independent copy
slice(begin, end) takes the same arguments as subarray, but it allocates a new buffer and copies the selected elements into it. The copy always starts at byteOffset 0 of its own buffer.
const a = new Uint8Array([10, 20, 30, 40]);
const copy = a.slice(1, 3);
console.log(copy.buffer === a.buffer); // false
console.log(copy.byteOffset); // 0
copy[0] = 0;
console.log(a[1]); // 20, the original is unchangedWhich methods share and which copy
| Method | Result | Shares the original buffer? |
|---|---|---|
| `subarray(b, e)` | New view, same type | Yes |
| `slice(b, e)` | New typed array, same type | No |
| `map(fn)` | New typed array, same type | No |
| `filter(fn)` | New typed array, same type | No |
| `toSorted()`, `toReversed()`, `with(i, v)` | New typed array, same type | No |
| `set(src, offset)` | Writes into `this`, returns `undefined` | Modifies in place |
| `fill`, `copyWithin`, `sort`, `reverse` | Returns `this` | Modifies in place |
set: Bulk Copy Into an Existing Array
target.set(source, offset) copies every element of source into target, starting at element index offset (default 0). The source can be a regular array, any array-like object, or another typed array. It is the fastest built-in way to copy many elements, and it replaces the loops you might otherwise write.
const target = new Uint8Array(6);
target.set([1, 2, 3]); // at index 0
target.set(new Uint8Array([9, 9]), 4); // at index 4
console.log(target); // Uint8Array [1, 2, 3, 0, 9, 9]The method has three behaviors that are easy to miss.
- If the source does not fit,
setthrows aRangeErrorand writes nothing. It does not truncate the source. - Each value goes through the target's conversion rules, so copying from a
Float32Arrayinto aUint8Arraytruncates and wraps. - If the source and target share a buffer and their ranges overlap, the result is correct: it is as if the source were copied out first.
try {
new Uint8Array(4).set([1, 2, 3], 2); // needs indices 2, 3, 4
} catch (e) {
console.log(e instanceof RangeError); // true
}
const bytes = new Uint8Array(3);
bytes.set(new Float32Array([1.9, -1, 256]));
console.log(bytes); // Uint8Array [1, 255, 0]
const a = new Uint8Array([1, 2, 3, 4, 5, 6]);
a.set(a.subarray(0, 4), 2); // overlapping ranges
console.log(a); // Uint8Array [1, 2, 1, 2, 3, 4]You cannot mix BigInt and Number element types. Calling set with a BigInt64Array source on a Float64Array target throws a TypeError.
Concatenating with set
Typed arrays have no concat method. The usual pattern allocates the total length once, then calls set with a moving offset:
function concatBytes(...arrays) {
const total = arrays.reduce((sum, arr) => sum + arr.length, 0);
const out = new Uint8Array(total);
let offset = 0;
for (const arr of arrays) {
out.set(arr, offset);
offset += arr.length;
}
return out;
}
console.log(concatBytes(new Uint8Array([1, 2]), new Uint8Array([3]), [4, 5]));
// Uint8Array [1, 2, 3, 4, 5]copyWithin(target, start, end) is the in-place relative of set. It moves elements around inside one array, and like set, it handles overlapping ranges correctly.
from and of: Building Typed Arrays
Each typed array constructor has two static factory methods. TypedArray.from(source, mapFn) accepts any iterable or array-like object and can apply a mapping function while it copies. TypedArray.of(...values) builds an array from its arguments.
console.log(Uint8Array.from({ length: 4 }, (_, i) => i * 10)); // Uint8Array [0, 10, 20, 30]
console.log(Uint16Array.from('123')); // Uint16Array [1, 2, 3], strings become numbers
console.log(Uint8Array.from(new Set([5, 6]))); // Uint8Array [5, 6]
console.log(Uint8Array.of(1, 2, 300)); // Uint8Array [1, 2, 44], 300 wrapsThe mapping function's result is converted to the element type, the same as any other write. from always copies, even when the source is a typed array over a buffer you already have.
To go the other way and get a regular array, use Array.from(typed) or [...typed]. You need this when you want an array that can grow, or when you need results that would not fit the element type.
How Typed Arrays Differ From Array
Typed arrays have a fixed length, so any method that changes the length is missing: push, pop, shift, unshift, splice, concat, flat, and flatMap are all absent, and so is the ES2023 toSpliced. Writing past the end does nothing and raises no error. It does not grow the array or add a property.
const t = new Uint8Array(2);
t[5] = 1;
console.log(t.length, t[5]); // 2 undefined
console.log(typeof t.push); // "undefined"
console.log(Array.isArray(t)); // falsemap keeps the element type
On a typed array, map returns a typed array of the same type, so the callback's results are converted. This silently corrupts results that do not fit:
const levels = new Uint8Array([100, 200]);
console.log(levels.map(x => x * 2)); // Uint8Array [200, 144]
console.log(Array.from(levels, x => x * 2)); // [200, 400]
console.log(levels.map(x => x / 3)); // Uint8Array [33, 66], fractions truncatedfilter also returns the same typed array type. The with(index, value) method converts the value too, and it throws a RangeError for an out-of-range index instead of ignoring it.
sort is numeric by default
Array.prototype.sort compares elements as strings unless you pass a comparator. TypedArray.prototype.sort compares numerically, and it sorts -0 before +0 and puts NaN last.
console.log([10, 9, 1, -2].sort()); // [-2, 1, 10, 9]
console.log(new Float64Array([10, 9, 1, -2]).sort()); // Float64Array [-2, 1, 9, 10]Other differences worth knowing
- Typed arrays have no holes. A new typed array is filled with zeros (or
0nfor BigInt types), notundefined. fill,indexOf,includes,at,find,findLast,join,reduce,every, andsomebehave as they do on arrays, apart from converting written values.JSON.stringifyof a typed array produces an object with index keys, such as{"0":1,"1":2}, not a JSON array. Convert to a regular array first if you need JSON.
Exercise
Given const a = new Uint8Array([1, 2, 3, 4]); const b = a.subarray(1); const c = b.slice(1); b[1] = 50; c[0] = 99;, what are the contents of a, b, and c?
Show answer
b is a view over elements 1 to 3 of a, so b[1] = 50 changes a[2]. c is a copy of b[1..] taken before that write, so it begins as [3, 4], and c[0] = 99 affects only c. Final values: a is [1, 2, 50, 4], b is [2, 50, 4], c is [99, 4].
Exercise
A function receives a Uint8Array named header (4 bytes) and a Uint8Array named body. Write code that produces a single new Uint8Array holding the header followed by the body, without using a loop over elements.
Show answer
Allocate once and use set with an offset: const out = new Uint8Array(header.length + body.length); out.set(header, 0); out.set(body, header.length);. Typed arrays have no concat, and set performs the copy as a bulk operation.
Exercise
Why does new Uint8Array([128, 255]).map(x => x + 1) return Uint8Array [129, 0], and how do you get [129, 256] instead?
Show answer
map on a typed array returns the same element type, so each result is converted to an 8-bit unsigned integer, and 256 wraps to 0. Use Array.from(arr, x => x + 1) to get a regular array, or write the results into a wider type such as Uint16Array.from(arr, x => x + 1).