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

Creating a DataView

Instantiating DataView with an ArrayBuffer, optional byte offset, and optional byte length parameters.

Creating a DataView

You'll learn how to instantiate a DataView to access an ArrayBuffer's raw bytes with precise control.

The Core Idea

A DataView acts like a flexible lens over an ArrayBuffer. To create one, you pass the buffer itself as the first argument. You can also specify where in that buffer your view should start (byte offset) and how many bytes it should cover (byte length). This lets you work with a specific portion of the buffer rather than the entire thing.

The Constructor Signature

new DataView(buffer, byteOffset, byteLength)
  • buffer (required): The ArrayBuffer you want to read from or write to
  • byteOffset (optional): Where to start in the buffer (defaults to 0)
  • byteLength (optional): How many bytes to include (defaults to buffer's remaining length)

Creating DataViews

// Create a 16-byte buffer
const buffer = new ArrayBuffer(16);

// View the entire buffer
const view1 = new DataView(buffer);

// View starting at byte 4, going to the end
const view2 = new DataView(buffer, 4);

// View 8 bytes starting at byte 4
const view3 = new DataView(buffer, 4, 8);

Think of It Like This

Imagine a long scroll of parchment (the ArrayBuffer). A DataView is a magnifying glass you position over a specific section. You decide where to place it and how wide your viewing window should be.

Key Takeaway: Create a DataView by passing an ArrayBuffer to its constructor; optionally specify a starting byte offset and length to focus on a specific portion of the buffer.