Sub topic 3
Typed Arrays as Views
An ArrayBuffer holds bytes, but it gives you no way to read or change them. To work with those bytes you need a view. A typed array is a view that treats a region of a buffer as a list of numbers that all have the same type. This chapter covers how views relate to the buffer underneath them, the ways to construct them, and the mistakes that come from confusing a view with a copy.
This chapter assumes you know core JavaScript, regular arrays, and the material from the previous chapter: an ArrayBuffer is a fixed-length block of raw bytes, and it cannot be indexed directly. Element types, value conversion, alignment rules, and methods such as subarray each get a chapter of their own later, so they appear here only where needed.
The View Model
A typed array object stores no data of its own. It keeps four pieces of information:
buffer: theArrayBufferthat holds the bytes.byteOffset: where in that buffer the view starts.length: how many elements the view exposes.- The element type, which fixes
BYTES_PER_ELEMENTand controls how bytes are read as numbers.
When you read view[i], the engine computes byteOffset + i * BYTES_PER_ELEMENT, reads that many bytes from the buffer, and returns the result as a number. A write runs the same steps in reverse. Every read and write goes to the buffer, so any number of views over the same buffer see the same bytes.
You can read all of these properties on any typed array:
const buf = new ArrayBuffer(16);
const view = new Uint16Array(buf, 4, 3);
console.log(view.buffer === buf); // true
console.log(view.byteOffset); // 4
console.log(view.length); // 3
console.log(view.byteLength); // 6 (length * BYTES_PER_ELEMENT)
console.log(view.BYTES_PER_ELEMENT); // 2
console.log(Uint16Array.BYTES_PER_ELEMENT); // 2, also on the constructorbyteLength is derived from the other values: it always equals length * BYTES_PER_ELEMENT. It covers the view's own region, which may be only part of the buffer. To get the size of the whole buffer, read view.buffer.byteLength.
Watching Two Views Share Memory
The quickest way to absorb the model is to change bytes through one view and read them back through another:
const buf = new ArrayBuffer(4);
const whole = new Uint8Array(buf); // bytes 0..3
const tail = new Uint8Array(buf, 2); // bytes 2..3
tail[0] = 7;
console.log(whole[2]); // 7, same byte
console.log(whole); // Uint8Array(4) [0, 0, 7, 0]
whole[3] = 42;
console.log(tail[1]); // 42tail[0] and whole[2] are two names for one byte. No copying or syncing happens between them because nothing is duplicated.
The Constructor Forms
Every typed array constructor (Uint8Array, Int16Array, Float64Array, and the others) accepts the same kinds of arguments. The kind of argument decides whether you get a view over existing memory or a new buffer.
| Call | New buffer allocated? | Contents |
|---|---|---|
| `new Uint8Array()` | Yes, 0 bytes | Empty |
| `new Uint8Array(n)` | Yes, `n * BYTES_PER_ELEMENT` bytes | All zeros |
| `new Uint8Array(arrayOrIterable)` | Yes | Elements copied and converted |
| `new Uint8Array(otherTypedArray)` | Yes | Elements copied and converted |
| `new Uint8Array(buffer)` | No | View over the whole buffer |
| `new Uint8Array(buffer, byteOffset)` | No | View from `byteOffset` to the end |
| `new Uint8Array(buffer, byteOffset, length)` | No | View of `length` elements |
Only the forms that take an ArrayBuffer (or SharedArrayBuffer) create a view over memory that already exists. Every other form allocates a new buffer behind the scenes, and you can reach that buffer through .buffer:
const zeros = new Float64Array(3);
console.log(zeros); // Float64Array(3) [0, 0, 0]
console.log(zeros.buffer.byteLength); // 24
const fromList = new Int16Array([1, 2, 3]);
console.log(fromList.buffer.byteLength); // 6
const fromIter = new Uint8Array(new Set([5, 6, 5])); // any iterable works
console.log(fromIter); // Uint8Array(2) [5, 6]
// Even a length-based array gets its own buffer, which you can view another way
const bytes = new Uint8Array(zeros.buffer);
console.log(bytes.length); // 24Number versus array of one number
A lone number means "length". An array containing that number means "these contents":
console.log(new Uint8Array(4)); // Uint8Array(4) [0, 0, 0, 0]
console.log(new Uint8Array([4])); // Uint8Array(1) [4]This mistake is easy to make when a function sometimes receives a count and sometimes receives data.
Copying from another typed array
Passing a typed array to a constructor always copies, even when both have the same type:
const original = new Uint8Array([1, 2, 3]);
const copy = new Uint8Array(original);
copy[0] = 100;
console.log(original[0]); // 1, unchanged
console.log(copy.buffer === original.buffer); // falseIf you want a second view over the same memory, pass the buffer, not the typed array:
const original = new Uint8Array([1, 2, 3]);
const alias = new Uint8Array(original.buffer, original.byteOffset, original.length);
alias[0] = 100;
console.log(original[0]); // 100Copying converts each element by value. The underlying bytes are not reinterpreted. new Uint8Array(new Uint16Array([300])) gives one element converted from 300 (you will see exactly how in the chapter on value conversion). It does not give the two raw bytes of 300. To read the raw bytes, build a Uint8Array over .buffer.
Offset and Length Arguments
When you pass a buffer, byteOffset is measured in bytes and length is measured in elements. The difference matters for any type wider than one byte:
const buf = new ArrayBuffer(16);
const a = new Float32Array(buf, 8); // from byte 8 to the end
console.log(a.length); // 2 ((16 - 8) / 4)
const b = new Float32Array(buf, 4, 2); // 2 elements = 8 bytes, bytes 4..11
console.log(b.byteLength); // 8If the region you ask for runs past the end of the buffer, the constructor throws a RangeError. It does not clamp the view to fit:
const buf = new ArrayBuffer(8);
try {
new Uint8Array(buf, 4, 10); // needs bytes 4..13, buffer has 8
} catch (e) {
console.log(e instanceof RangeError); // true
}Requirements on where offsets may fall, such as a Uint32Array starting on a multiple of 4, are covered in the chapter on sharing a buffer.
How Typed Arrays Behave Like and Unlike Arrays
Typed arrays support indexing, length, for...of, spread, and most of the familiar iteration methods. In other ways they behave differently because they are fixed views over fixed memory:
const t = new Uint8Array(3);
console.log(Array.isArray(t)); // false
console.log(typeof t.push); // "undefined", no push, pop, splice, shift
t[5] = 9; // out of range: silently ignored
console.log(t[5]); // undefined
console.log(t.length); // 3
t.foo = 1; // ordinary named properties still work
console.log(Object.keys(t)); // ["0", "1", "2", "foo"]
console.log([...t]); // [0, 0, 0], a regular Array copyA write outside the view's range is not an error, even in strict mode. It does nothing. A bug that computes a bad index will therefore drop data silently instead of throwing, so check indexes yourself when correctness depends on them.
Every element always exists. There are no holes, and every slot holds a number of the view's type. You cannot store undefined, strings, or objects in a typed array. Values are converted on write.
The shared %TypedArray% parent
All typed array constructors inherit from one hidden constructor, which the specification calls %TypedArray%. That is where methods such as subarray and set come from. You can reach it, but you cannot call it:
const TypedArray = Object.getPrototypeOf(Uint8Array);
console.log(new Uint8Array(2) instanceof TypedArray); // true
try {
new TypedArray(2);
} catch (e) {
console.log(e instanceof TypeError); // true, it is abstract
}This gives you a type check that works for every typed array: x instanceof TypedArray. ArrayBuffer.isView(x) is also true for typed arrays, but it returns true for DataView objects as well.
Calling a concrete constructor without new, as in Uint8Array(4), also throws a TypeError.
Common Errors
Using `.buffer` as if it held only the view's bytes
The .buffer property returns the whole buffer, not the view's region. Code that receives a view and passes view.buffer to an API that expects "these bytes" can leak or corrupt neighboring data:
const all = new Uint8Array([1, 2, 3, 4, 5, 6]);
const middle = new Uint8Array(all.buffer, 2, 2); // [3, 4]
console.log(new Uint8Array(middle.buffer)); // all 6 bytes, not 2
console.log(new Uint8Array(middle.buffer, middle.byteOffset, middle.byteLength)); // [3, 4]This comes up often in Node.js. Buffer is a Uint8Array subclass, and small Buffer values are carved out of a shared memory pool of about 8 KB. Buffer.from('hi').buffer is usually much larger than 2 bytes and contains unrelated data. Always carry byteOffset and byteLength with the buffer, or call .slice() when you need a standalone copy.
Expecting a copy to stay in sync, or a view to stay independent
If two pieces of code both hold views over one buffer, a write through one shows up in the other. If they hold copies, it does not. When results look stale or change unexpectedly, compare a.buffer === b.buffer to find out which case you are in.
Treating length as a byte count
length counts elements. byteLength counts bytes. They are equal only for 1-byte types. Allocating new Float64Array(bytes.length) to hold bytes.length bytes allocates eight times too much.
Exercise
Given const a = new Uint8Array([10, 20, 30, 40]); const b = new Uint8Array(a.buffer, 1, 2); const c = new Uint8Array(b); b[0] = 99; c[1] = 0;, what are the contents of a, b, and c?
Show answer
a is [10, 99, 30, 40], b is [99, 30], and c is [20, 0]. b is a view over bytes 1 and 2 of a's buffer, so b[0] = 99 changes a[1]. c was built from a typed array, so it is a copy in its own buffer. It holds [20, 30] at creation, and c[1] = 0 changes only c.
Exercise
Write a function asBytes(view) that takes any typed array and returns a Uint8Array covering exactly the same bytes, sharing memory and not copying. Check it with asBytes(new Uint16Array(new ArrayBuffer(8), 2, 2)).
Show answer
function asBytes(view) { return new Uint8Array(view.buffer, view.byteOffset, view.byteLength); }. For the test input the result has byteOffset 2 and length 4, and its buffer is the original 8-byte buffer. Using view.length here would be wrong, because the Uint8Array length argument counts bytes, while view.length counts 2-byte elements.
Exercise
Why does new Uint8Array(5) give five zeros while new Uint8Array([5]) gives one element with value 5? Which constructor form never allocates new memory?
Show answer
A single number argument is read as a length, so the constructor allocates a 5-byte buffer filled with zeros. An array argument is read as contents to copy. Only the forms that take an ArrayBuffer (or SharedArrayBuffer), optionally with byteOffset and length, create a view without allocating a new buffer.