Sub topic 1
Why Binary Data in JavaScript
JavaScript started as a language for small scripts on web pages. Its basic data types are strings, objects, and one number type, and none of them gives you control over individual bytes. Modern programs often need that control. They decode images, play audio, talk to network protocols, upload files, hand buffers to the GPU, and share memory with WebAssembly. This chapter explains why regular arrays and strings are a poor fit for that work. It also introduces the three tools the rest of the tutorial covers: ArrayBuffer, typed arrays, and DataView.
Prerequisites
This chapter and the ones after it assume you already know:
- Core JavaScript syntax, plus regular arrays and their methods (
push,map,slice). - That every JavaScript
Numberis a 64-bit IEEE 754 floating-point value, and how integers differ from fractions within that type. - Hexadecimal notation (
0xffis 255), and that a byte is 8 bits holding a value from 0 to 255. - Promises and
fetch, for the later chapter on I/O.
You do not need any C, assembly, or systems programming background.
What a regular array cannot promise
A regular JavaScript Array is a flexible, general-purpose container. It can hold any mix of values, it grows and shrinks, and it can have holes. Engines store arrays in clever internal formats, but the language makes no promise about how many bytes each element uses or where those bytes sit in memory.
const arr = [1, 2, 3];
arr.push('four', { five: 5 });
arr[10] = 11;
console.log(arr.length); // 11
console.log(arr[7]); // undefined (a hole)
const bytes = new Uint8Array(3);
bytes[0] = 1;
bytes[5] = 9; // out of range: silently ignored
console.log(bytes.length); // 3
console.log(bytes[5]); // undefined
console.log(typeof bytes.push); // "undefined"The Uint8Array above behaves very differently. It has a fixed length, every element is exactly one byte, and every element is a number from 0 to 255. It has no push, because it cannot grow. These limits are the reason it is useful. When a file format says "the next 4 bytes are a 32-bit integer", you need a structure whose layout matches that description exactly.
Numbers have a storage format
A JavaScript Number is always a 64-bit float. Binary formats written by other programs use many other formats: 8-bit unsigned integers for pixels, 16-bit signed integers for audio samples, 32-bit floats for 3D vertex positions. If you only have Number, you cannot express "store this as a 32-bit float" or see what that choice does to the value.
const f64 = new Float64Array([0.1]);
const f32 = new Float32Array([0.1]);
console.log(f64[0]); // 0.1
console.log(f32[0]); // 0.10000000149011612The Float32Array really does store 4 bytes per element, so 0.1 gets rounded to the nearest 32-bit float. When you read it back, it is widened to a 64-bit Number again, and the rounding shows. This is the behavior you need when you exchange data with a GPU or a C library that expects float. You also need to know it happens.
Memory size you can predict
Binary types also make memory use exact. A regular array of a million numbers may take very different amounts of memory depending on the engine and on what the array contains. A typed array tells you its size.
const n = 1_000_000;
const samples = new Float32Array(n);
console.log(samples.BYTES_PER_ELEMENT); // 4
console.log(samples.byteLength); // 4000000
console.log(samples[0]); // 0 (always zero-initialized)Audio buffers, vertex arrays, and image pixel data often hold millions of elements. A compact layout that the engine never has to check or convert per element matters a great deal at that size.
How it was done before
Before typed arrays existed, developers worked with binary data through "binary strings". Each character held one byte in its char code, and code pulled bytes out with charCodeAt. To make XMLHttpRequest return raw bytes, people used tricks such as overriding the MIME type to text/plain; charset=x-user-defined.
// The old way: one byte per character
const binary = String.fromCharCode(0x89, 0x50, 0x4e, 0x47);
const firstByte = binary.charCodeAt(0) & 0xff;
console.log(firstByte.toString(16)); // "89"
// The modern way: a real byte array
const modern = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);
console.log(modern[0].toString(16)); // "89"Binary strings were slow and easy to corrupt. Any step that treated the string as text, such as re-encoding or normalizing it, could change the bytes. Building multi-byte integers meant combining characters by hand with shifts. Typed arrays first shipped in browsers around 2011 to support WebGL, and ES2015 made them part of the language itself.
Where you meet binary data today
Many platform APIs now produce or consume binary data directly:
| Area | API or source | What it uses |
|---|---|---|
| Network | `fetch` with `response.arrayBuffer()`, WebSocket with `binaryType = 'arraybuffer'` | `ArrayBuffer` |
| Files | `Blob`, `File`, `FileReader` | `ArrayBuffer` |
| Graphics | WebGL, WebGPU vertex and texture data | `Float32Array`, `Uint16Array`, `Uint8Array` |
| Canvas | `ImageData.data` | `Uint8ClampedArray` |
| Audio | Web Audio `AudioBuffer.getChannelData()` | `Float32Array` |
| Security | `crypto.getRandomValues`, Web Crypto digests | integer typed arrays, `ArrayBuffer` |
| WebAssembly | `WebAssembly.Memory.buffer` | `ArrayBuffer` |
| Node.js | `Buffer`, streams, `fs` | `Uint8Array` subclass |
The three-part model
JavaScript divides binary work into storage and access. An ArrayBuffer is the storage: a fixed block of raw bytes with no type and no way to read it directly. To read or write those bytes, you create a view over them. A typed array view, such as Uint8Array or Float32Array, treats the bytes as a list of same-sized numbers. A DataView reads and writes a value of any type at any byte offset, and you choose the byte order on each call.
Because views do not own the bytes, several views can look at the same buffer at once. That design is powerful, and it also causes most of the surprises later chapters cover. These include alignment errors, platform-dependent byte order, and edits through one view appearing in another.
A first real task: recognizing a file type
Many file formats begin with a fixed sequence of "magic bytes". Every PNG file starts with the 8 bytes 89 50 4E 47 0D 0A 1A 0A. Checking for them is a typical small binary task. A string comparison is the wrong tool here. You need to compare bytes.
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
function isPng(bytes) {
if (bytes.length < PNG_SIGNATURE.length) return false;
return PNG_SIGNATURE.every((b, i) => bytes[i] === b);
}
const header = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00]);
console.log(isPng(header)); // true
console.log(isPng(new Uint8Array([0x47, 0x49, 0x46]))); // false (starts like a GIF)In a real program, header would come from await file.arrayBuffer() or await response.arrayBuffer(), wrapped in a Uint8Array. The later chapter on I/O shows that step.
When you do not need binary types
Typed arrays are not a faster replacement for every array. If you store mixed values, need push and splice, or work with small lists of application data, a regular Array is simpler and fits better. Use binary types when you meet one of these situations:
- An API gives you or expects an
ArrayBufferor typed array. - The data has a defined byte layout, such as a file format, a network protocol, or a GPU buffer.
- You have large numeric data and want compact, predictable memory.
- You share memory with WebAssembly or between workers.
Exercises
Exercise
You run const a = new Uint8Array(4); a[4] = 7; and then console.log(a.length, a[4]);. What prints, and why does a regular array behave differently?
Show answer
It prints 4 undefined. A typed array has a fixed length, so writing past the end is silently ignored. A regular array would grow to length 5 and store 7 at index 4.
Exercise
Why does new Float32Array([0.1])[0] print 0.10000000149011612 while new Float64Array([0.1])[0] prints 0.1?
Show answer
A Float32Array stores each element in 4 bytes as a 32-bit float, so 0.1 is rounded to the nearest 32-bit value. Reading it back widens that rounded value to a 64-bit Number, which shows the rounding. Float64Array uses the same format as Number, so no rounding happens.
Exercise
For each case, choose a regular Array or a binary type: (1) a list of user names, (2) 48,000 audio samples per second for Web Audio, (3) the first 8 bytes of an uploaded file, to detect its format.
Show answer
(1) A regular Array, because the values are strings with no byte layout. (2) A Float32Array, because Web Audio uses 32-bit float samples and the data is large. (3) A Uint8Array over the file's ArrayBuffer, because format detection compares exact byte values.