Typed Arrays and ArrayBuffer
Most JavaScript values are high-level: numbers, strings, objects. But files, images, audio, network protocols, cryptography and WebGL all deal in raw bytes. Typed arrays give JavaScript efficient, fixed-type access to binary data: an ArrayBuffer is a block of raw memory, and a typed array such as Uint8Array or Float64Array is a view that reads and writes that memory as numbers of one specific type. DataView reads mixed types with explicit byte order. ES2026 adds built-in base64 and hex conversion for Uint8Array.
In One Minute
new ArrayBuffer(16)allocates 16 bytes of memory, all zero; you can't read it directly.- Typed arrays view a buffer as fixed-size numbers:
Uint8Array(bytes),Int32Array,Float64Arrayand others. - Several views can share one buffer: changing one changes what the others see.
DataViewreads and writes any type at any byte offset, with explicit endianness (byte order).Uint8Array.fromBase64,toBase64,fromHexandtoHex(ES2026) convert bytes to and from text.
ArrayBuffer and Views
An ArrayBuffer is a fixed-length block of raw bytes. To use it, you create a view:
const buffer = new ArrayBuffer(8);
console.log(buffer.byteLength);
const bytes = new Uint8Array(buffer);
const words = new Uint32Array(buffer);
bytes[0] = 255;
bytes[1] = 1;
console.log(Array.from(bytes));
console.log(words[0]);
console.log(bytes.length, words.length);8
[255, 1, 0, 0, 0, 0, 0, 0]
511
8 2Explanation: the 8-byte buffer is seen as 8 one-byte numbers through Uint8Array, and as 2 four-byte numbers through Uint32Array. Both views share the same memory: after writing 255 and 1 into the first two bytes, the first 32-bit word reads as 255 + 1 × 256 = 511 (on little-endian machines, which almost all are; see byte order below).
Typed Array Types
| Type | Bytes per element | Range or kind |
|---|---|---|
Int8Array | 1 | -128 to 127 |
Uint8Array | 1 | 0 to 255 |
Uint8ClampedArray | 1 | 0 to 255, clamped (used for canvas pixels) |
Int16Array / Uint16Array | 2 | -32,768 to 32,767 / 0 to 65,535 |
Int32Array / Uint32Array | 4 | About ±2.1 billion / 0 to about 4.3 billion |
Float16Array | 2 | Half-precision float (ES2025) |
Float32Array | 4 | Single-precision float |
Float64Array | 8 | Double precision, the same as a JavaScript number |
BigInt64Array / BigUint64Array | 8 | 64-bit integers as BigInts |
Creating Typed Arrays
const zeros = new Uint8Array(4);
const fromArray = new Int16Array([1, -2, 300]);
const fromIterable = Float64Array.from(new Set([0.5, 1.5]));
const view = new Uint8Array(new ArrayBuffer(16), 4, 8);
console.log(zeros, Array.from(fromArray), Array.from(fromIterable));
console.log(view.byteOffset, view.length, view.buffer.byteLength);{ 0: 0, 1: 0, 2: 0, 3: 0 } [1, -2, 300] [0.5, 1.5]
4 8 16(This site's console shows a typed array like an object with numbered keys; Array.from turns it into a regular array for printing. The browser console and Node.js show Uint8Array(4) [0, 0, 0, 0].)
A view can cover only part of a buffer: new Uint8Array(buffer, 4, 8) starts at byte 4 and covers 8 bytes.
Fixed Types Mean Conversion
A typed array element always holds its declared type. Values are converted on write, which can surprise you:
const bytes = new Uint8Array(4);
bytes[0] = 256;
bytes[1] = -1;
bytes[2] = 3.9;
bytes[3] = "12";
console.log(Array.from(bytes));
const clamped = new Uint8ClampedArray([300, -5, 3.5]);
console.log(Array.from(clamped));
const floats = new Float32Array([0.1]);
console.log(floats[0]);[0, 255, 3, 12]
[255, 0, 4]
0.10000000149011612Explanation: Uint8Array wraps values modulo 256 (256 becomes 0, -1 becomes 255) and truncates decimals. Uint8ClampedArray clamps to 0 to 255 and rounds, which is what you want for pixel colors. Float32Array stores less precision than JavaScript numbers, so 0.1 comes back slightly different.
Typed arrays have most array methods (map, filter, reduce, slice, sort, includes, at, toSorted...), but a fixed length: no push, pop or splice. subarray(start, end) creates a new view on the same memory, while slice copies.
DataView and Byte Order
Binary file formats and network protocols mix types (a 2-byte count, then 4-byte values) and specify byte order: big-endian (most significant byte first, common in network protocols) or little-endian (least significant first, used by most CPUs). DataView reads and writes any type at any offset, with the order you choose:
const buffer = new ArrayBuffer(8);
const view = new DataView(buffer);
view.setUint16(0, 2026);
view.setUint16(2, 2026, true);
view.setFloat32(4, 120.5);
console.log(Array.from(new Uint8Array(buffer)).map((b) => b.toString(16).padStart(2, "0")).join(" "));
console.log(view.getUint16(0), view.getUint16(2, true), view.getUint16(2));
console.log(view.getFloat32(4));07 ea ea 07 42 f1 00 00
2026 2026 59911
120.5Explanation: 2026 is 0x07EA. Written big-endian (the default for DataView), its bytes are 07 ea; written little-endian (third argument true), they're ea 07. Reading those little-endian bytes as big-endian gives a completely different number, 59911 (0xEA07). Always read with the same byte order that was used to write.
Base64 and Hex (ES2026)
Bytes often travel as text: base64 in JSON and data URLs, hex for hashes and keys. ES2026 adds direct conversions to Uint8Array, replacing the old btoa/atob workarounds (which only handle Latin-1 strings):
const bytes = new TextEncoder().encode("Fee: $120 for Zoë");
const base64 = bytes.toBase64();
const hex = bytes.toHex();
console.log(base64);
console.log(hex);
const back = Uint8Array.fromBase64(base64);
console.log(new TextDecoder().decode(back));
console.log(Uint8Array.fromHex("cafe").join(","));
console.log(new Uint8Array([251, 255]).toBase64({ alphabet: "base64url" }));RmVlOiAkMTIwIGZvciBab8Or
4665653a202431323020666f72205a6fc3ab
Fee: $120 for Zoë
202,254
-_8=The URL-safe alphabet (last line) uses - and _ instead of + and /, so the text can go in URLs and file names.
| Method | Does |
|---|---|
bytes.toBase64(options?) | Encodes to base64 (alphabet: "base64url" for URL-safe output) |
Uint8Array.fromBase64(text, options?) | Decodes base64 to bytes |
bytes.toHex() | Encodes to lowercase hex |
Uint8Array.fromHex(text) | Decodes hex to bytes |
bytes.setFromBase64(text) / setFromHex(text) | Decodes into an existing array |
TextEncoder turns a string into UTF-8 bytes and TextDecoder turns bytes back into a string; together with these methods, they handle any text, including accented letters and emoji.
Where Binary Data Appears
| API | Gives or takes |
|---|---|
fetch | await response.arrayBuffer(), await response.bytes() (a Uint8Array) |
| Files and Blobs | await file.arrayBuffer(), await blob.bytes() |
| Canvas | ctx.getImageData() returns pixels in a Uint8ClampedArray |
| Web Crypto | crypto.getRandomValues(new Uint8Array(16)), crypto.subtle.digest("SHA-256", bytes) |
| WebSockets, WebRTC | Binary messages as ArrayBuffer |
| Node.js | Buffer is a Uint8Array subclass; fs.readFile returns one |
| WebGL, WebGPU, Web Audio | Vertex data, audio samples in Float32Array |
const data = new TextEncoder().encode("Navika paid $120");
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", data));
console.log(digest.length, "bytes");
console.log(digest.toHex().slice(0, 16) + "...");32 bytes
aaa2e5055d0e8da4...Shared Memory and Atomics (Optional)
A SharedArrayBuffer can be shared between the main thread and Web Workers (or Node.js worker threads), so they read and write the same memory without copying. Because two threads can then change the same bytes at once, Atomics provides operations that complete without interruption (Atomics.add, Atomics.compareExchange) and ways for threads to wait for each other (Atomics.wait, Atomics.notify):
const shared = new Int32Array(new SharedArrayBuffer(4));
Atomics.add(shared, 0, 120);
Atomics.add(shared, 0, 85);
console.log(Atomics.load(shared, 0));
console.log(Atomics.compareExchange(shared, 0, 205, 0), Atomics.load(shared, 0));205
205 0In browsers, SharedArrayBuffer is available only on cross-origin isolated pages (served with special Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers), a protection against Spectre-style attacks. Most applications never need it; message passing (postMessage) is simpler and safer.
In Practice
The Fee Tracker stores a year of daily payment totals compactly: 365 values in a Float64Array (2,920 bytes, with no per-item object overhead), computes statistics, and exports a checksum as hex:
const daily = new Float64Array(365);
for (let day = 0; day < 365; day++) daily[day] = ((day * 37) % 500) + 0.5;
const total = daily.reduce((sum, v) => sum + v, 0);
const busiest = daily.indexOf(Math.max(...daily));
console.log(daily.byteLength, "bytes");
console.log("total:", total.toFixed(2), "busiest day index:", busiest);
const firstWeek = daily.subarray(0, 7);
firstWeek[0] = 999;
console.log(daily[0]);
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", daily));
console.log("checksum:", digest.toHex().slice(0, 12));2920 bytes
total: 92092.50 busiest day index: 27
999
checksum: 9ada77abbc55Changing firstWeek[0] changed daily[0] too, because subarray returns a view on the same memory. The checksum is SHA-256 over the raw bytes of all 365 numbers, which changes if any value changes.
Common Mistakes
Expecting typed arrays to grow. They have a fixed length: no push. Allocate the size you need, or copy into a larger one (or use a resizable ArrayBuffer with maxByteLength).
Writing values that don't fit. They wrap or clamp silently. Choose a larger type.
Confusing subarray and slice. subarray shares memory; slice copies.
Ignoring byte order. Read with the same endianness used to write; DataView defaults to big-endian.
Practice
Challenge: Encode the string "Advitha:45" as UTF-8 bytes, print them as hex, then decode the hex back into the string.
Show solution
const hex = new TextEncoder().encode("Advitha:45").toHex();
console.log(hex);
console.log(new TextDecoder().decode(Uint8Array.fromHex(hex)));416476697468613a3435
Advitha:45Key Takeaways
| Task | Code |
|---|---|
| Allocate bytes | new ArrayBuffer(16) or new Uint8Array(16) |
| Text to bytes | new TextEncoder().encode(text) |
| Bytes to text | new TextDecoder().decode(bytes) |
| Mixed binary format | new DataView(buffer).getUint16(0, true) |
| Base64 | bytes.toBase64(), Uint8Array.fromBase64(s) |
| Hex | bytes.toHex(), Uint8Array.fromHex(s) |
Was this tutorial helpful?