Course contentsShow
← JavaScript
Lesson 2326 of 2,72348. Working with Binary DataFree lesson

Buffer, ByteOffset, and BYTES_PER_ELEMENT

Accessing the underlying ArrayBuffer, starting position, and element size metadata.

Buffer, ByteOffset, and BYTES_PER_ELEMENT

You'll learn how to access metadata about a typed array's underlying memory structure.

The Core Idea

Every typed array is actually a view into a chunk of raw binary data called an ArrayBuffer. Three properties let you peek "under the hood" to understand exactly where and how your typed array sits in memory:

  • buffer: The underlying ArrayBuffer that holds the actual bytes
  • byteOffset: How many bytes from the buffer's start your view begins
  • BYTES_PER_ELEMENT: How many bytes each element in this type of array occupies

Think of it like an apartment building: the buffer is the entire building, byteOffset tells you which floor your apartment starts on, and BYTES_PER_ELEMENT tells you how much space each item in your apartment takes up.

Understanding the Metadata

const buffer = new ArrayBuffer(16); // 16 bytes of raw memory
const view = new Int32Array(buffer, 4, 2); // Start at byte 4, length 2

console.log(view.buffer === buffer);     // true - same underlying memory
console.log(view.byteOffset);            // 4 - starts 4 bytes in
console.log(view.BYTES_PER_ELEMENT);     // 4 - Int32 uses 4 bytes per number
console.log(view.byteLength);            // 8 - total bytes (2 elements × 4 bytes)

These properties are crucial when you need to create multiple views into the same buffer, share memory between different typed arrays, or understand memory alignment for performance-critical operations.

Key Takeaway: Use buffer, byteOffset, and BYTES_PER_ELEMENT to understand a typed array's memory layout—where it sits in the underlying ArrayBuffer, where it starts, and how much space each element consumes.