Glossary / DataView

DataView

DataView provides byte-offset-based reads and writes over an ArrayBuffer, allowing each operation to specify a numeric representation and endianness. It is suited to binary formats with heterogeneous fields, alignment constraints, or a defined network byte order. Typed arrays are simpler for homogeneous numeric sequences; DataView is more explicit for protocol parsing.

Reading a binary record

const view = new DataView(buffer);
const version = view.getUint8(0);
const length = view.getUint16(1, false); // false = big-endian
const amount = view.getFloat32(3, true); // true = little-endian

DataView’s multibyte accessors default to big-endian when the optional littleEndian argument is omitted or false. Typed arrays instead use native byte order. Methods such as getInt32, getBigUint64, and setFloat64 read/write specific widths and representations. Invalid offsets throw RangeError, so validate the buffer size before reading. Reads and writes share the underlying buffer; another view can alter the bytes.

Parser design

Treat binary input as untrusted. Check minimum header size, version, declared length, and overflow before calculating offsets. Avoid unaligned assumptions and bounds mistakes. Document whether fields are signed, scaled, endian-specific, or reserved. Use tests with truncated, oversized, malformed, and boundary-value inputs.

Interview questions

  1. Why use DataView instead of Uint32Array for a network packet? It controls field offsets and byte order explicitly.
  2. What is the default DataView endianness? Big-endian.
  3. What happens on an out-of-range read? A RangeError is thrown.
  4. Does DataView copy the buffer? No, it is a view over the original buffer.

References