Sub topic 1
Why Binary Data in JavaScript
Prerequisites
This chapter assumes you know core JavaScript syntax and regular arrays. It also assumes you know how JavaScript numbers work, including integers versus floating point, and that you can read hexadecimal and think in bits and bytes.
Why Binary Data in JavaScript
A regular JavaScript Array holds values of any type, can grow and shrink, and hides its memory layout from you. That flexibility gets in the way when the code has to work with exact bytes, which happens with file formats, network protocols, images, audio, WebGL and WebAssembly. Those tasks need fixed-size numbers packed into contiguous memory. JavaScript provides this through three pieces that work together.
ArrayBuffer: A Block of Raw Bytes
An ArrayBuffer is a fixed-length block of memory, and every byte in it starts at zero. You cannot index it directly. It only stores the bytes, and a view decides how they are read.
Typed Arrays as Views
A typed array is a view that reads a buffer's bytes as numbers of a single type. Two views can share one buffer:
const buf = new ArrayBuffer(8);
console.log(buf.byteLength); // 8
const bytes = new Uint8Array(buf);
const words = new Uint32Array(buf);
console.log(bytes.length, words.length); // 8 2
words[0] = 0x01020304;
console.log(bytes[0]); // 4 on little-endian platforms (most hardware)Both views read and write the same eight bytes, so a write through one view shows up in the other.
Choosing an Element Type
| Type | Bytes | Range or kind |
|---|---|---|
| Int8Array / Uint8Array | 1 | -128..127 / 0..255 |
| Uint8ClampedArray | 1 | 0..255, clamped |
| Int16Array / Uint16Array | 2 | 16-bit integers |
| Int32Array / Uint32Array | 4 | 32-bit integers |
| Float32Array / Float64Array | 4 / 8 | IEEE floating point |
Choose the smallest type whose range fits your data, or the type that the format or API you are working with requires.
What Happens When a Value Does Not Fit
Typed arrays never throw an error when a value is out of range. They convert it silently:
console.log(new Uint8Array([255, 256, -1, 1.7])); // Uint8Array [255, 0, 255, 1]
console.log(new Int8Array([127, 128])); // Int8Array [127, -128]
console.log(new Uint8ClampedArray([300, -5, 1.5])); // Uint8ClampedArray [255, 0, 2]Integer types drop the fractional part of a value, then wrap it modulo 2^n. Uint8ClampedArray limits values to the range 0 to 255 and rounds them, sending exact halves to the nearest even number.
Exercise
What do new Int16Array([40000])[0] and new Uint8ClampedArray([2.5])[0] return?
Show answer
The Int16Array element is -25536, because 40000 wraps to 40000 - 65536. The Uint8ClampedArray element is 2, because 2.5 is an exact half and rounds to the nearest even number.