Typed Arrays, ArrayBuffer and DataView: Working with Binary Data in JavaScript
Binary data in JavaScript: typed array types and how values wrap, clamp or round, ArrayBuffer and shared views, subarray vs slice, DataView and endianness, TextEncoder for strings, base64 and hex helpers, resizable and transferable buffers, Float16Array, and where binary data shows up in real code.
kvi5hnuCode Sprout team member8 min readOn this page
Regular JavaScript arrays hold any mix of values and grow freely. That flexibility costs memory and speed, and it's useless when you need raw bytes: reading a PNG header, sending a binary network message, hashing a file, processing audio samples, uploading data to the GPU. For that, JavaScript has typed arrays: fixed-length arrays of numbers of one specific machine type, stored compactly in a block of memory called an ArrayBuffer.
The typed array types
| Type | Element | Range |
|---|---|---|
Int8Array / Uint8Array | 8-bit integer, 1 byte | -128 to 127 / 0 to 255 |
Uint8ClampedArray | 8-bit unsigned, clamped | 0 to 255 (out-of-range values clamp) |
Int16Array / Uint16Array | 16-bit integer, 2 bytes | -32,768 to 32,767 / 0 to 65,535 |
Int32Array / Uint32Array | 32-bit integer, 4 bytes | about ±2.1 billion / 0 to about 4.3 billion |
Float16Array (ES2025) | 16-bit float, 2 bytes | about 3 significant digits |
Float32Array | 32-bit float, 4 bytes | about 7 significant digits |
Float64Array | 64-bit float, 8 bytes | a normal JavaScript number |
BigInt64Array / BigUint64Array | 64-bit integer, 8 bytes | BigInt values (5n) |
Each constructor has a BYTES_PER_ELEMENT property (1, 2, 4 or 8). There's no constructor called TypedArray; "typed array" is the umbrella name for all of them.
Creating typed arrays
const zeros = new Float64Array(4); // length 4, all 0
const pixel = Uint8ClampedArray.of(255, 128, 0, 255);
const fromArray = new Int16Array([10, 20, 30]); // copies (and converts) values
const codes = Uint8Array.from("abc", (ch) => ch.charCodeAt(0));
console.log(zeros, pixel.length, fromArray[1], codes);
console.log(Array.isArray(fromArray), Float32Array.BYTES_PER_ELEMENT);
Float64Array(4) [ 0, 0, 0, 0 ] 4 20 Uint8Array(3) [ 97, 98, 99 ]
false 4
Typed arrays differ from normal arrays in three ways:
- Fixed length. The length is set at creation;
push,pop,shift,unshiftandsplicedon't exist, and assigning tolengthdoes nothing. - Always initialized, to
0(or0n). - Every element is a number of the declared type: values you store are converted silently.
Conversion: truncating, wrapping, clamping, rounding
console.log(Uint8Array.of(1.9, 255, 256, -1, 300));
console.log(Int8Array.of(127, 128, 200));
console.log(Uint8ClampedArray.of(1.5, 2.5, 300, -5));
console.log(new Float32Array([0.1])[0], new Float16Array([0.1])[0]);
Uint8Array(5) [ 1, 255, 0, 255, 44 ]
Int8Array(3) [ 127, -128, -56 ]
Uint8ClampedArray(4) [ 2, 2, 255, 0 ]
0.10000000149011612 0.0999755859375
- Integer types truncate fractions and wrap around (modulo 2⁸, 2¹⁶ or 2³²): 256 becomes 0, -1 becomes 255, 300 becomes 44. No error, no warning.
Uint8ClampedArrayclamps to 0..255 and rounds to the nearest integer (ties go to the even number, so 1.5 and 2.5 both become 2). The HTML canvas uses it for pixel data, so brightening a pixel never wraps a bright value to black.- Float types round to the nearest representable value, losing precision.
Array methods still work
Typed arrays have almost all the non-length-changing array methods: map, filter, reduce, forEach, find, includes, indexOf, join, fill, sort, reverse, at, toSorted, with, and more:
const readings = new Int32Array([5, 1, 10]);
console.log(readings.toSorted(), [5, 1, 10].toSorted());
console.log(new Uint8Array([200]).map((x) => x * 2));
console.log(Array.from(new Uint8Array([200]), (x) => x * 2));
Int32Array(3) [ 1, 5, 10 ] [ 1, 10, 5 ]
Uint8Array(1) [ 144 ]
[ 400 ]
Two differences: typed arrays sort numerically by default (no comparator needed, unlike normal arrays), and map returns the same typed array type, so results are converted (200 × 2 wraps to 144). Use Array.from(typed, fn) when the results need to be ordinary numbers.
ArrayBuffer and views
Every typed array is a view onto an ArrayBuffer, a fixed-size block of raw bytes. An ArrayBuffer by itself has no way to read or write its bytes; you always go through a view. Several views can share one buffer, each interpreting the same bytes differently:

const buffer = new ArrayBuffer(4);
const bytes = new Uint8Array(buffer);
const halves = new Uint16Array(buffer);
bytes[0] = 1;
bytes[1] = 1;
console.log(buffer.byteLength, halves.length, bytes.buffer === halves.buffer);
console.log(halves[0]); // the two bytes read together: 1 + 1 * 256
4 2 true
257
(That last value assumes a little-endian machine, which is what essentially all current phones, PCs and servers are. More on byte order below.)
A view can cover part of a buffer: new Int32Array(buffer, byteOffset, length). The byte offset must be a multiple of the element size.
subarray vs slice
const temps = new Int16Array([18, 21, 24, 19, 15, 12]);
const evening = temps.subarray(4); // a new view of the same memory
const backup = temps.slice(4); // a new buffer with copied values
temps[5] = -3;
console.log(evening, backup);
console.log(evening.byteOffset, evening.byteLength, evening.buffer.byteLength);
Int16Array(2) [ 15, -3 ] Int16Array(2) [ 15, 12 ]
8 4 12
subarray is cheap (no copying) but changes show through both ways; slice is independent. Every typed array has buffer, byteOffset and byteLength, and length * BYTES_PER_ELEMENT === byteLength always holds.
Copying in with set()
target.set(source, offset) copies a normal or typed array into a typed array at a position, very fast:
const packet = new Uint8Array(6);
packet.set([1, 2, 3]);
packet.set(Uint8Array.of(9, 9), 4);
console.log(packet);
Uint8Array(6) [ 1, 2, 3, 0, 9, 9 ]
DataView and endianness
A 32-bit integer occupies 4 bytes, and machines disagree about their order. Little-endian stores the least significant byte first; big-endian stores the most significant byte first. Typed arrays use the machine's native order (little-endian in practice), but file formats and network protocols specify their own, often big-endian ("network byte order").
A DataView reads and writes values of any type at any byte offset, with the byte order you choose:
const buf = new ArrayBuffer(8);
const view = new DataView(buf);
view.setUint32(0, 0x01020304); // big-endian by default
view.setUint32(4, 0x01020304, true); // true = little-endian
console.log(new Uint8Array(buf));
console.log(view.getUint32(0).toString(16), view.getUint32(0, true).toString(16));
console.log(view.getUint16(1), view.getInt8(0));
Uint8Array(8) [
1, 2, 3, 4,
4, 3, 2, 1
]
1020304 4030201
515 1
- Getters and setters exist for every type:
getInt8,getUint16,getFloat32,getBigInt64,setFloat64, and so on. - The last argument is
littleEndian: omitted orfalsemeans big-endian,truemeans little-endian. - Offsets are in bytes and don't need alignment (
getUint16(1)reads bytes 1 and 2).
Rule of thumb: use Uint8Array for raw bytes, other typed arrays for bulk numeric data in native order (images, audio, WebGL), and DataView for parsing structured binary formats.
Parsing a binary header
// The first 24 bytes of a PNG file: signature, then the IHDR chunk with width and height
const pngHeader = Uint8Array.of(
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x01, 0xe0,
);
function pngSize(bytes) {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const isPng = view.getUint32(0) === 0x89504e47;
const chunkType = String.fromCharCode(...bytes.subarray(12, 16));
return { isPng, chunkType, width: view.getUint32(16), height: view.getUint32(20) };
}
console.log(pngSize(pngHeader));
{ isPng: true, chunkType: 'IHDR', width: 640, height: 480 }
PNG stores integers big-endian, which is DataView's default. Note how the view is created from the typed array's buffer, byteOffset and byteLength, so it works even when the bytes are a slice of a larger buffer.
Strings and bytes
Text must be encoded into bytes (almost always UTF-8) and decoded back. TextEncoder and TextDecoder are available in browsers and Node:
const encoded = new TextEncoder().encode("héllo");
console.log(encoded, encoded.length);
console.log(new TextDecoder().decode(encoded));
Uint8Array(6) [ 104, 195, 169, 108, 108, 111 ] 6
héllo
"héllo" has 5 characters but 6 bytes: é takes two bytes in UTF-8. Byte lengths and string lengths differ for non-ASCII text (article 13), which matters for size limits, protocols and storage.
Base64 and hex (ES2026)
Binary data often travels as text in base64 or hexadecimal. Uint8Array now converts directly:
const bytes = new TextEncoder().encode("Hi!");
console.log(bytes.toBase64(), bytes.toHex());
console.log(new TextDecoder().decode(Uint8Array.fromBase64("SGkh")));
console.log(Uint8Array.fromHex("cafe"));
SGkh 486921
Hi!
Uint8Array(2) [ 202, 254 ]
toBase64 also accepts { alphabet: "base64url" } for URL-safe output. These methods are recent (Node 25 and current browsers); older code uses btoa/atob (which only handle "binary strings") or Node's Buffer.
Resizable and transferable buffers (ES2024)
const growable = new ArrayBuffer(4, { maxByteLength: 16 });
const view = new Uint8Array(growable); // a length-tracking view
growable.resize(8);
console.log(growable.resizable, view.length);
const original = new Uint8Array([1, 2, 3]).buffer;
const moved = original.transfer(); // move the memory, no copy
console.log(original.detached, original.byteLength, moved.byteLength);
true 8
true 0 3
- Resizable buffers (
maxByteLength) can grow or shrink in place, and views created without a fixed length track the new size, which is useful for streams and growing data. transfer()moves the memory to a new buffer and detaches the old one (its length becomes 0 and views on it stop working). Transferring to Web Workers withpostMessage(data, [buffer])works the same way and avoids copying large data.
Where you'll meet binary data
fetchresponses:await response.arrayBuffer()orresponse.bytes()(aUint8Array).- Files and uploads:
await file.arrayBuffer(),Blob. - Canvas pixels:
ctx.getImageData(...).datais aUint8ClampedArrayof RGBA bytes. - Crypto:
crypto.getRandomValues(new Uint8Array(16)),crypto.subtle.digest("SHA-256", bytes). - WebSockets, WebGL/WebGPU buffers, Web Audio sample data, WebAssembly memory.
- Node's
Bufferis a subclass ofUint8Arraywith extra methods.
Common questions
Are typed arrays faster than normal arrays?
For numeric work on large data, usually yes: elements are stored compactly with a fixed type, which is cache-friendly and avoids type checks, and they use far less memory (1 byte per element for Uint8Array versus 8 or more for a normal array element). For small, mixed or growing collections, normal arrays are the right tool.
Why did new Uint8Array([300])[0] give 44?
Unsigned 8-bit values wrap modulo 256: 300 - 256 = 44. Use Uint8ClampedArray for clamping, or a wider type if values can exceed 255.
What is endianness, briefly?
The order of bytes within a multi-byte number. Little-endian puts the least significant byte first (x86, ARM in practice); big-endian puts the most significant first (many file formats and network protocols). DataView lets you choose explicitly.
How do I convert a typed array to a normal array?
Array.from(typed) or [...typed]. Going the other way, pass the array to the constructor: new Float64Array(array).
Summary
- Typed arrays are fixed-length arrays of one numeric type (
Uint8Array,Int32Array,Float64Array,Float16Array,BigInt64Array...), zero-initialized; stored values are converted, wrapping, clamping or rounding silently. - They support most array methods;
sortis numeric, andmapkeeps the typed array type. - An
ArrayBufferis raw memory; typed arrays and DataViews are views on it, and views can share a buffer.subarrayshares memory,slicecopies. DataViewreads and writes any type at any byte offset with explicit endianness (big-endian by default).TextEncoder/TextDecoderconvert strings to and from UTF-8 bytes;toBase64,fromBase64,toHexandfromHexconvert bytes to text forms.- Buffers can be resizable and transferable (ES2024).
Practice Questions
What does this print?
const a = new Uint8Array(2);
a[0] = 256 + 7;
a[1] = -2;
console.log(a);
Answer
Uint8Array(2) [ 7, 254 ]. 263 wraps to 7, and -2 wraps to 254.
What's the difference between bytes.subarray(2, 4) and bytes.slice(2, 4)?
Answer
Both return a 2-element Uint8Array, but subarray is a view sharing the same memory (changes are visible both ways), while slice copies the bytes into a new buffer.
Using a DataView, write a 16-bit unsigned value 513 at offset 0 in big-endian order. What are bytes 0 and 1?
Answer
new DataView(buf).setUint16(0, 513) stores bytes 2 and 1 (513 = 2 × 256 + 1, most significant byte first).
Why is new TextEncoder().encode("€").length equal to 3?
Answer
UTF-8 encodes the euro sign (U+20AC) as three bytes. The string's length is 1, but its byte length is 3.
Previous: WeakMap, WeakSet, WeakRef and FinalizationRegistry: Memory-Friendly References in JavaScript
Next: JavaScript Regular Expressions: Literals, Character Classes, Quantifiers, Anchors and Groups

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.