Sub topic 9
DataView: Reading and Writing Mixed Types
Typed arrays work well when every element in a buffer has the same type and sits at an aligned offset. Real binary data is often messier. A file header might hold a 1-byte version, then a 2-byte id, then a 4-byte float, packed together with no padding and stored in a byte order your machine does not use. DataView handles that kind of data.
This chapter assumes you have read the earlier chapters on ArrayBuffer, typed array views, element types, alignment, and endianness. You should know what "little-endian" and "big-endian" mean and why a Uint32Array cannot start at byte offset 1.
The Working Model
A DataView is a typed-array-free window over an ArrayBuffer. It has no element type and no length in elements. Each read or write names three things:
- The value type, which is part of the method name, such as
getUint16orsetFloat32. - A byte offset, counted from the start of the view.
- The byte order, passed as an optional
littleEndianboolean. It defaults tofalse, which means big-endian.
Because the type and offset are chosen per call, one view can read a uint8 at byte 0 and a float32 at byte 3 from the same buffer, which typed arrays cannot do.
Creating a DataView
The constructor is new DataView(buffer, byteOffset, byteLength). Both numeric arguments are optional. If you leave them out, the view covers the whole buffer.
const buf = new ArrayBuffer(16);
const dv = new DataView(buf, 4, 8);
console.log(dv.byteOffset, dv.byteLength); // 4 8
dv.setUint8(0, 0xff); // view offset 0 is buffer byte 4
console.log(new Uint8Array(buf)[4]); // 255
try {
dv.getUint8(8); // one past the end of the view
} catch (e) {
console.log(e instanceof RangeError); // true
}Offsets passed to get and set count from the view's own start, not from the start of the buffer. A DataView has no alignment requirement, so byteOffset can be any integer within the buffer.
The get and set Methods
Every getX method has a matching setX method. The set methods take (byteOffset, value, littleEndian), and the get methods take (byteOffset, littleEndian).
| Method pair | Bytes | Value type | Endianness argument |
|---|---|---|---|
| `getInt8` / `setInt8` | 1 | Number | ignored |
| `getUint8` / `setUint8` | 1 | Number | ignored |
| `getInt16` / `setInt16` | 2 | Number | yes |
| `getUint16` / `setUint16` | 2 | Number | yes |
| `getInt32` / `setInt32` | 4 | Number | yes |
| `getUint32` / `setUint32` | 4 | Number | yes |
| `getFloat32` / `setFloat32` | 4 | Number | yes |
| `getFloat64` / `setFloat64` | 8 | Number | yes |
| `getBigInt64` / `setBigInt64` | 8 | BigInt | yes |
| `getBigUint64` / `setBigUint64` | 8 | BigInt | yes |
ES2025 also adds getFloat16 and setFloat16. Check your target runtimes before you rely on them.
Here is explicit byte order in action:
const dv = new DataView(new ArrayBuffer(6));
dv.setUint16(0, 0x1234); // big-endian by default
dv.setUint32(2, 0xdeadbeef, true); // little-endian
console.log(dv.getUint8(0).toString(16)); // "12"
console.log(dv.getUint8(2).toString(16)); // "ef"
console.log(dv.getUint32(2, true).toString(16)); // "deadbeef"The big-endian write puts the most significant byte 0x12 first. The little-endian write puts the least significant byte 0xef first. This output is the same on every platform. A Uint32Array uses the host's byte order, but a DataView always does exactly what each call tells it.
Writing a Packed Record
A DataView can write fields of different sizes at unaligned offsets. The function below writes an 11-byte header with a running offset: a 1-byte tag, a 2-byte version, a 4-byte count, and a 4-byte float. All multi-byte fields are little-endian.
const LE = true;
function writeHeader(count, scale) {
const buf = new ArrayBuffer(11);
const dv = new DataView(buf);
let o = 0;
dv.setUint8(o, 0x42); o += 1; // tag 'B'
dv.setUint16(o, 2, LE); o += 2; // version, at offset 1
dv.setUint32(o, count, LE); o += 4; // count, at offset 3
dv.setFloat32(o, scale, LE); o += 4; // scale, at offset 7
return buf;
}
function readHeader(buf) {
const dv = new DataView(buf);
return {
tag: dv.getUint8(0),
version: dv.getUint16(1, LE),
count: dv.getUint32(3, LE),
scale: dv.getFloat32(7, LE),
};
}
const h = writeHeader(1000, 0.5);
const hex = [...new Uint8Array(h)]
.map((b) => b.toString(16).padStart(2, '0'))
.join(' ');
console.log(hex); // "42 02 00 e8 03 00 00 00 00 00 3f"
console.log(readHeader(h)); // { tag: 66, version: 2, count: 1000, scale: 0.5 }None of the offsets 1, 3, or 7 are valid for a Uint16Array or Uint32Array. The hex dump also shows little-endian order: 1000 is 0x000003e8, stored as e8 03 00 00. The float 0.5 is 0x3f000000, stored as 00 00 00 3f. A later chapter covers parsing a full format. This example shows only the DataView mechanics.
Value Conversion on set
The set methods convert values the same way typed arrays do. Integers wrap modulo 2^n, fractions are truncated toward zero, and floats are rounded to the nearest representable value. No method clamps. DataView has nothing like Uint8ClampedArray.
const dv = new DataView(new ArrayBuffer(8));
dv.setUint8(0, 300);
console.log(dv.getUint8(0)); // 44 (300 - 256)
dv.setInt16(0, 40000);
console.log(dv.getInt16(0)); // -25536 (40000 - 65536)
dv.setFloat32(0, 0.1);
console.log(dv.getFloat32(0)); // 0.10000000149011612
dv.setBigUint64(0, 2n ** 64n - 1n);
console.log(dv.getBigInt64(0)); // -1n, same bits read as signed
try {
dv.setBigInt64(0, 1); // Number instead of BigInt
} catch (e) {
console.log(e instanceof TypeError); // true
}You can write with one type and read with another, which reinterprets the same bits. The setBigUint64 and getBigInt64 pair above shows this: all 64 bits set reads as -1n when signed.
Common Errors
Ignoring a typed array's byteOffset
Data often arrives as a Uint8Array that is itself a slice of a bigger buffer, for example from subarray or a Node.js Buffer. Wrapping only .buffer makes the view start at byte 0 of the whole buffer.
const whole = new Uint8Array([0, 1, 2, 3, 4, 5]);
const part = whole.subarray(2); // bytes 2, 3, 4, 5
const wrong = new DataView(part.buffer);
console.log(wrong.getUint8(0)); // 0, from the start of the whole buffer
const right = new DataView(part.buffer, part.byteOffset, part.byteLength);
console.log(right.getUint8(0)); // 2Always pass byteOffset and byteLength when you build a DataView from a typed array.
Reading past the end
A read fails if offset + size is greater than byteLength, not only if offset is out of range. getUint32(5) on an 8-byte view throws a RangeError, because it needs bytes 5 through 8. Negative offsets also throw. When parsing untrusted input, check lengths before reading, or catch the RangeError and report a truncated input.
Detached buffers
If the underlying buffer is transferred to a worker or with transfer(), any access through the old DataView throws a TypeError. Later chapters cover transfer.
Expecting array behavior
A DataView has no length, no index access (dv[0] is undefined), and no iteration methods. To loop over bytes or call map, create a Uint8Array over the same range.
Choosing Between DataView and a Typed Array
| Need | Better choice | Reason |
|---|---|---|
| Many values of one type, host byte order | Typed array | Indexing, bulk methods, fastest loops |
| Fields of different types in one record | DataView | Type chosen per call |
| Unaligned fields | DataView | No alignment rule |
| A fixed byte order regardless of platform | DataView | Explicit `littleEndian` argument |
| Large arrays of big-endian samples | DataView in a loop, or byte-swap a copy | Typed arrays cannot change byte order |
Modern engines optimize DataView calls well, so speed is rarely a reason to avoid it for parsing headers and records. For tight numeric loops over millions of same-typed, native-order values, a typed array is still simpler and usually faster.
Exercise
What does this code print, and why? const dv = new DataView(new ArrayBuffer(4)); dv.setUint16(0, 0xabcd); console.log(dv.getUint16(0, true).toString(16));
Show answer
It prints "cdab". The write uses the default big-endian order and stores bytes ab cd. The read uses little-endian order, so it treats cd as the high byte and ab as the low byte, which gives 0xcdab.
Exercise
A function receives a Uint8Array named packet, which may be a subarray of a larger buffer. It must read a little-endian uint32 starting at byte 2 of packet. Write the one or two lines that do this correctly.
Show answer
const dv = new DataView(packet.buffer, packet.byteOffset, packet.byteLength); const value = dv.getUint32(2, true); Passing byteOffset and byteLength makes offset 2 refer to byte 2 of packet, not byte 2 of the underlying buffer.
Exercise
DataView has no 24-bit methods. Write a function getUint24BE(dv, offset) that reads an unsigned 24-bit big-endian integer, and say which error it throws if fewer than 3 bytes remain.
Show answer
function getUint24BE(dv, offset) { return (dv.getUint8(offset) << 16) | dv.getUint16(offset + 1); } The high byte is shifted left 16 bits and combined with the following big-endian uint16. The result is at most 0xffffff, so the bitwise OR stays positive. If fewer than 3 bytes remain, getUint16 (or getUint8) throws a RangeError.