skip to content

In JavaScript, what is the relationship between an ArrayBuffer and a typed array such as Uint8Array, and what happens when two views share one buffer?

level: juniorimportance: must knowfreq 35%

answer

  1. bytes versus interpretation
  2. buffer has no indexed access
  3. views hold no data of their own
  4. offset in bytes, length in elements
  5. only a buffer argument shares memory

basics

~20 s

An ArrayBuffer is raw bytes you cannot index directly; a typed array is a view reading those bytes as numbers of one type. Two views on one buffer see each other's writes, each through its own type.

solid answer

~40 s

An `ArrayBuffer` holds raw bytes and nothing else: `buffer[0]` is `undefined`, and its size is `byteLength`, not `length`. To read or write those bytes you create a view, either a typed array or a `DataView`. A typed array such as `Uint8Array` or `Int32Array` fixes an element type, and its index is an element position rather than a byte position. The view stores no data of its own, so two views over one buffer alias the same memory: after `u8[0] = 255`, an `Int8Array` over that buffer reads `-1`, because the same bits are decoded as two's complement. Only passing the buffer shares memory; `new Uint8Array(otherTypedArray)` copies. In `new Uint16Array(buffer, 2, 3)` the offset counts bytes and the length counts elements, so that view spans six bytes starting at byte 2.

code

javascript · 9 lines
javascript
const buffer = new ArrayBuffer(4);
const u8 = new Uint8Array(buffer);
const i8 = new Int8Array(buffer);

u8[0] = 255;
console.log(i8[0]); // -1
console.log(buffer[0]); // undefined
console.log(buffer.byteLength); // 4
console.log(u8.buffer === i8.buffer); // true

go deeper

for a junior

Recall the split: the buffer is bytes, the typed array is how you read them. Be ready to predict what a second view of a different type shows after a write through the first.

for a middle

Explain how an index becomes a byte position through the element size and byteOffset, and which constructor forms share memory rather than copy. Mention the alignment RangeError unprompted.

for a senior

Treat aliasing as a design fact: a function that returns a view hands the caller write access to the shared bytes. Say when you would hand out a view and when you would take a copy.

for a principal

Frame it as an ownership question for a codebase handling binary data: who may hold a view, who may write through it, and whether APIs accept buffers, views or both as a settled convention.

## Bytes and interpretation are separate objects JavaScript splits binary data into two kinds of object. An **`ArrayBuffer`** is a block of raw bytes, the thing other languages call a byte array. It has a size, reported by `byteLength`, and a new one starts out filled with zeros, but it has no element type and no indexed access. `buffer[0]` is `undefined` and `buffer.length` is `undefined`, because a buffer has neither. A **view** gives those bytes a meaning. There are two families: - A **typed array** such as `Uint8Array`, `Int16Array` or `Float64Array` treats the bytes as a run of numbers of one type, and you index it much like an array. There is no global called `TypedArray`; the word names the family. - A **`DataView`** has no element type at all. Each getter or setter call names the type and the byte offset, which suits formats that mix types. ## How an indexed read works A typed array holds a reference to its buffer plus a range, not a private copy of the data. Reading `view[i]` goes through three steps: 1. Multiply `i` by the element size, `BYTES_PER_ELEMENT`, and add the view's `byteOffset`. 2. Read that many bytes from the buffer. 3. Decode them according to the element type, for example as two's complement for a signed integer. A write runs the same steps in reverse. That is why a view's index is an element position, while every offset on the buffer is a byte position. ## Two views, one buffer ```js const buffer = new ArrayBuffer(4); const u8 = new Uint8Array(buffer); const i8 = new Int8Array(buffer); u8[0] = 255; console.log(i8[0]); // -1 console.log(u8.buffer === i8.buffer); // true ``` Both views address the same byte. Its bits are `11111111`, which is 255 as an unsigned number and -1 in two's complement. The buffer keeps no record of which view wrote a byte or what type was meant, so the reader's type alone decides the value. Views of different widths can overlap too. A `Uint32Array` over this buffer would read all four of those bytes as one number, in the platform's byte order, so code that has to behave the same on every machine does not depend on that overlap and uses a `DataView` instead. ## The constructor argument decides whether memory is shared | Call | Memory | Result | |---|---|---| | `new Uint8Array(buffer)` | shared | a view of the whole buffer | | `new Uint16Array(buffer, 2, 3)` | shared | 3 elements, 6 bytes, starting at byte 2 | | `new Uint8Array(4)` | new, zeroed | 4 elements over an internal buffer | | `new Uint8Array(otherTypedArray)` | copied | a separate buffer, with each element converted | | `new Uint8Array([1, 2])` | new | a separate buffer filled from the array | Only the first two forms alias existing bytes. A copy looks identical until someone writes to the source, which makes the difference easy to miss in a test that only reads. ## The traps a beginner meets first - **Units.** `length` counts elements and `byteLength` counts bytes. `new Int32Array(8)` has 8 elements and 32 bytes, while `new ArrayBuffer(8)` has 8 bytes. - **Alignment.** `byteOffset` must be a multiple of the element size, or the constructor throws `RangeError`. With no `length` argument, a fixed-length buffer's size must also be a multiple, so `new Uint32Array(new ArrayBuffer(6))` throws. - **Bounds.** A view's range has to fit inside the buffer, and a range that does not fit throws `RangeError` at construction. - **Calling without `new`.** Typed array constructors throw `TypeError` when called as plain functions. - **Telling them apart.** `ArrayBuffer.isView(x)` is `true` for a typed array or a `DataView` and `false` for the buffer itself. Every view also exposes `buffer`, `byteOffset` and `byteLength`, so you can always reach the memory behind it. ## Why the split exists Binary data rarely has one type all the way through. A file or a message can start with a few header bytes and continue with a long run of samples, and the split lets you put a `Uint8Array` over the header and a `Float32Array` over the samples without copying anything. Since views are cheap and share memory, reinterpreting bytes costs almost nothing. The price is aliasing: when two parts of a program hold views of one buffer, a write through either is visible through both, whether or not that was intended. When you need an independent copy, take one explicitly, with `slice()` on the buffer or on a typed array.

  • What does `new Int32Array(8)` allocate, and how does it differ from `new ArrayBuffer(8)`?
    `new Int32Array(8)` creates 8 elements over an internal buffer of 32 bytes, all zero, which you can reach through its `buffer` property. `new ArrayBuffer(8)` creates 8 bytes with no element type and no indexing. A number passed to a typed array constructor counts elements, and a number passed to `ArrayBuffer` counts bytes.
  • What do `new Uint32Array(new ArrayBuffer(6))` and `new Uint32Array(new ArrayBuffer(8), 1)` do, and why?
    Both throw `RangeError`. Elements of a `Uint32Array` are 4 bytes, so `byteOffset` must be a multiple of 4, and when `length` is omitted a fixed-length buffer's size must be a multiple of 4 as well. A `DataView` has no such requirement, which is one reason it is used for packed data.
  • How can code tell whether a value is a buffer or a view of one?
    `ArrayBuffer.isView(x)` returns `true` for any typed array and for a `DataView`, and `false` for an `ArrayBuffer` or a regular array. From a view, the `buffer`, `byteOffset` and `byteLength` properties tell you which memory it covers, which is how you check whether two views overlap.

  • A typed array copies the bytes out of the ArrayBuffer it is given.
  • You can read a byte directly with buffer[0] on an ArrayBuffer.
  • The length argument of a typed array constructor over a buffer counts bytes.
  • new Uint8Array(otherTypedArray) shares memory with the source array.
  • An ArrayBuffer remembers which element type was written into it.