Sub topic 6
Sharing a Buffer: byteOffset, length, and Alignment
This chapter assumes you already know three things from earlier chapters. An ArrayBuffer is a fixed block of raw bytes. A typed array is a view that reads and writes those bytes as numbers. Each element type has a fixed size, such as 1 byte for Uint8Array and 4 bytes for Uint32Array. This chapter shows how to point several views at different parts of one buffer, and the rules the constructor checks before it allows that.
The three-argument constructor
When you pass an ArrayBuffer to a typed array constructor, you can also pass two numbers that pick which part of the buffer the view covers:
// new TypedArray(buffer, byteOffset, length)
const buf = new ArrayBuffer(16);
const all = new Uint8Array(buf); // bytes 0..15, 16 elements
const header = new Uint32Array(buf, 0, 2); // bytes 0..7, 2 elements
const body = new Float64Array(buf, 8, 1); // bytes 8..15, 1 element
console.log(all.length, header.length, body.length); // 16 2 1The two numbers use different units, and mixing them up is a common source of bugs:
byteOffsetis measured in bytes from the start of the buffer.lengthis measured in elements of the view's type.
So new Uint32Array(buf, 8, 2) starts at byte 8 and covers 2 × 4 = 8 bytes, ending at byte 16. It does not cover 2 bytes.
If you leave out length, the view runs from byteOffset to the end of the buffer. If you leave out both numbers, the view covers the whole buffer.
Views share the same bytes
None of these views own any memory. A write through one view is visible through every other view that covers the same bytes:
const buf = new ArrayBuffer(16);
const all = new Uint8Array(buf);
const header = new Uint32Array(buf, 0, 2);
const body = new Float64Array(buf, 8, 1);
header[0] = 0xffffffff;
console.log(Array.from(all.subarray(0, 4))); // [255, 255, 255, 255]
all[4] = 7;
console.log(header[1]); // 7 on little-endian platforms
body[0] = 1.5;
console.log(all.subarray(8).some((b) => b !== 0)); // true: bytes 8..15 changed
console.log(header[0]); // still 4294967295: body does not overlap headerThe result header[1] === 7 depends on byte order. The next chapter covers byte order in detail. For now, note that whenever two views of different element sizes overlap, the result depends on the platform's byte order.
Properties that describe a view
Every typed array reports where it sits in its buffer:
| Property | Unit | Meaning |
|---|---|---|
| `buffer` | none | The `ArrayBuffer` the view reads from |
| `byteOffset` | bytes | Where the view starts inside the buffer |
| `byteLength` | bytes | How many bytes the view covers |
| `length` | elements | How many elements the view has |
| `BYTES_PER_ELEMENT` | bytes | Size of one element (also on the constructor) |
For any fixed-length view, byteLength === length * BYTES_PER_ELEMENT. The view covers bytes byteOffset up to, but not including, byteOffset + byteLength.
const buf = new ArrayBuffer(16);
const v = new Uint16Array(buf, 6, 3);
console.log(v.buffer === buf); // true
console.log(v.byteOffset); // 6
console.log(v.length); // 3
console.log(v.byteLength); // 6
console.log(Uint16Array.BYTES_PER_ELEMENT); // 2The rules the constructor enforces
The constructor checks the arguments before it creates the view, and throws a RangeError if any of these rules fail:
byteOffsetmust be a multiple ofBYTES_PER_ELEMENT. This is the alignment rule.- If
lengthis given,byteOffset + length * BYTES_PER_ELEMENTmust not exceedbuffer.byteLength. - If
lengthis omitted,byteOffsetmust not exceedbuffer.byteLength, and the remaining bytesbuffer.byteLength - byteOffsetmust be a multiple ofBYTES_PER_ELEMENT.
const buf = new ArrayBuffer(8);
function attempt(label, make) {
try {
const v = make();
console.log(label, 'ok, length', v.length);
} catch (e) {
console.log(label, e.constructor.name);
}
}
attempt('aligned offset', () => new Uint32Array(buf, 4)); // ok, length 1
attempt('misaligned', () => new Uint32Array(buf, 1)); // RangeError (rule 1)
attempt('too long', () => new Uint32Array(buf, 4, 2)); // RangeError (rule 2)
attempt('offset past end', () => new Uint8Array(buf, 9)); // RangeError (rule 3)
attempt('offset at end', () => new Uint8Array(buf, 8)); // ok, length 0
attempt('leftover bytes', () => new Uint32Array(new ArrayBuffer(6))); // RangeError (rule 3)
attempt('explicit length', () => new Uint32Array(new ArrayBuffer(6), 0, 1)); // ok, length 1The last two lines show a subtle point. A 6-byte buffer cannot be viewed whole as Uint32Array, because 2 bytes would be left over. If you pass an explicit length of 1, the view covers bytes 0..3, and the constructor accepts it because the trailing bytes are outside the view.
Why alignment exists
A typed array finds element i at byte address byteOffset + i * BYTES_PER_ELEMENT. When byteOffset is a multiple of the element size, every element starts on an aligned address. Many CPUs load aligned values in a single instruction. Some CPUs run misaligned loads more slowly, and a few historically could not do them at all. Requiring alignment lets the engine compile view[i] into a plain native memory access with no checks for each element. This is part of why typed arrays are fast.
The rule applies only to typed arrays. DataView, covered two chapters from now, reads any type at any byte offset because it assembles each value byte by byte. When a binary format puts a 4-byte integer at byte 1, DataView is the right tool.
| Need | Use |
|---|---|
| Many same-type values at an aligned offset | Typed array view |
| Mixed types, or values at odd offsets | `DataView` |
| Same-type values at a misaligned offset, accessed often | Copy to a fresh buffer, then a typed array |
The `.buffer` gotcha
A view's buffer property returns the whole underlying buffer, not just the part the view covers. Code that receives a typed array and rebuilds a view from arr.buffer alone will silently pick up bytes that belong to someone else:
const big = new Uint8Array([10, 20, 30, 40, 50, 60, 70, 80]);
const part = big.subarray(2, 6); // [30, 40, 50, 60], byteOffset 2
// Wrong: ignores byteOffset and length
const wrong = new Uint8Array(part.buffer);
console.log(wrong.length); // 8, and starts at 10
// Right: carry the offset and length across
const right = new Uint8Array(part.buffer, part.byteOffset, part.byteLength);
console.log(Array.from(right)); // [30, 40, 50, 60]This happens often in real code. Node.js Buffer objects are Uint8Array subclasses, and small buffers are often carved out of a shared memory pool, so buf.byteOffset is often not zero. Bytes from fetch or a Blob usually start at offset 0, but any function that accepts a Uint8Array from a caller should assume the view might be a slice of something larger.
Reinterpreting the bytes as a wider type adds the alignment rule on top:
const big = new Uint8Array([10, 20, 30, 40, 50, 60, 70, 80]);
const part = big.subarray(2, 6); // byteOffset 2, byteLength 4
// Works for Uint16: offset 2 is a multiple of 2
const asU16 = new Uint16Array(part.buffer, part.byteOffset, part.byteLength / 2);
console.log(asU16.length); // 2
// Fails for Uint32: offset 2 is not a multiple of 4
try {
new Uint32Array(part.buffer, part.byteOffset, part.byteLength / 4);
} catch (e) {
console.log(e instanceof RangeError); // true
}
// Fix: copy into a fresh buffer, which always starts at offset 0
const copy = part.slice();
const asU32 = new Uint32Array(copy.buffer);
console.log(copy.byteOffset, asU32.length); // 0 1Copying costs time and memory but always gives an aligned start. For a single read, new DataView(part.buffer, part.byteOffset, part.byteLength).getUint32(0, true) avoids the copy entirely.
Planning a layout
When you design a layout for several arrays in one buffer, place the widest element types first. This keeps every offset aligned without padding:
const count = 3;
const bytes = count * 8 + count * 4 + count * 1; // 39
const buf = new ArrayBuffer(bytes);
const positions = new Float64Array(buf, 0, count); // bytes 0..23
const ids = new Uint32Array(buf, count * 8, count); // bytes 24..35
const flags = new Uint8Array(buf, count * 8 + count * 4, count); // bytes 36..38
console.log(positions.byteOffset, ids.byteOffset, flags.byteOffset); // 0 24 36If you put flags first, ids would start at byte 3 and the constructor would throw. You would then need to add padding bytes to round each offset up to the next multiple of the element size.
Exercise
Given const buf = new ArrayBuffer(10);, which of these succeed, and what is the length of each successful view? (a) new Float32Array(buf, 4) (b) new Float32Array(buf, 4, 1) (c) new Int16Array(buf, 2, 4) (d) new Int16Array(buf, 3, 1)
Show answer
(a) throws a RangeError: no length is given, and the 6 remaining bytes are not a multiple of 4. (b) succeeds with length 1, covering bytes 4..7. (c) succeeds with length 4: 2 + 4 × 2 = 10, which fits exactly. (d) throws a RangeError because offset 3 is not a multiple of 2.
Exercise
A function receives data, a Uint8Array with byteOffset 5 and byteLength 8, and does new Float64Array(data.buffer)[0] to read a double. Name the two problems and give a correct way to read the double, assuming little-endian bytes.
Show answer
First, data.buffer ignores byteOffset, so the view starts at byte 0 of the whole buffer instead of byte 5. Second, even with the offset passed in, 5 is not a multiple of 8, so new Float64Array(data.buffer, 5, 1) would throw a RangeError. A correct read is new DataView(data.buffer, data.byteOffset, data.byteLength).getFloat64(0, true). Alternatively, new Float64Array(data.slice().buffer)[0] copies the bytes to an aligned buffer first.
Exercise
You need one buffer holding 5 Uint8 values, 5 Uint16 values, and 5 Float32 values with no padding. Give an order and the byteOffset of each view, plus the total byteLength.
Show answer
Put the widest type first: Float32Array at offset 0 (20 bytes), Uint16Array at offset 20 (10 bytes, and 20 is a multiple of 2), Uint8Array at offset 30 (5 bytes). The total is 35 bytes.