Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Typed arrays: element count, view bytes, and buffer bytes

Distinguish the backing buffer object (`.buffer`), the view's element count (`.length`) and byte count (`.byteLength`), and the whole buffer's current byte count (`.buffer.byteLength`).

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

const buffer = new ArrayBuffer(byteCount);
const view = new Uint16Array(buffer, byteOffset, elementCount);
view.buffer       // backing buffer object
view.length       // element count in the view
view.byteLength   // byte count in the view
buffer.byteLength // current byte count of the entire buffer

view.buffer returns the same backing object without copying data: an ArrayBuffer or, for a view of shared memory, a SharedArrayBuffer. view.length counts elements, while view.byteLength counts bytes in the view: view.length * view.BYTES_PER_ELEMENT. view.buffer.byteLength gives the whole buffer's current byte count, not its maximum. SharedArrayBuffer has its own byteLength getter. These are read-only properties, not methods.

new Uint16Array(n) allocates storage for n elements. By contrast, new Uint16Array(buffer, byteOffset, length) creates a view without copying: the offset is in bytes and the length is in elements. A misaligned offset or a range that exceeds the buffer throws RangeError. If a recipient should receive only the view's data, pass a copy of its byte range, not view.buffer, which exposes bytes outside the view too.

With a resizable ArrayBuffer (ECMAScript 2024), omitting length makes the view track however many whole elements fit from its offset to the end of the buffer. An explicit length fixes the view's range. Shrinking the buffer can put the view out of bounds: view.length and view.byteLength then return 0. Growing the buffer again can bring the view back into bounds. Check support in your target runtime before using resizing.

Transferring an ArrayBuffer on the web can detach the original buffer. view.buffer still returns that same object, but buffer.byteLength, view.length, and view.byteLength return 0. Zero alone does not prove detachment: a buffer or view can simply be empty.

Examples

{
  const buffer = new ArrayBuffer(16);
  const view = new Uint16Array(buffer, 4, 3);
  console.log(`${view.buffer === buffer} | ${view.length} | ${view.byteLength} | ${buffer.byteLength}`);
}

Result

true | 3 | 6 | 16

The result `true | 3 | 6 | 16` confirms that the view uses the same buffer: it starts at byte offset 4 and covers 3 elements of 2 bytes each in a 16-byte buffer.

Related lessons

  • JavaScript · Lesson 5 · Advanced · Version: 4

Sources