What is a DataView and when would you use it over a TypedArray?
Short answer
DataView lets you read and write multiple numeric types at arbitrary byte offsets within an ArrayBuffer, and lets you control endianness (byte order). Use it when parsing binary formats with mixed data types, like file headers or network protocols.
Advertisement
AModel answer
DataView lets you read and write multiple numeric types at arbitrary byte offsets within an ArrayBuffer, and lets you control endianness (byte order). Use it when parsing binary formats with mixed data types, like file headers or network protocols.
const buffer = new ArrayBuffer(4);
const view = new DataView(buffer);
view.setInt16(0, 300, true); // little-endian
console.log(view.getInt16(0, true)); // 300Real-world example
Parsing a binary file format like a PNG or WAV header, where fields have different types and sizes.
Likely follow-ups
- What is endianness and why does it matter?
Related topics