Skip to content
jshacks.dev
Fundamentals

Typed Arrays and ArrayBuffer in JavaScript Explained

An ArrayBuffer is raw memory, and typed arrays or a DataView are views onto it. See element types, overflow, shared memory, byte order and slice or subarray.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript and Node.js logos.

Ordinary JavaScript arrays hold anything, resize freely and cost memory for every element. That flexibility is wrong for the jobs that need bytes: image pixels, audio samples, file headers, network packets, WebAssembly memory, cryptographic keys. For those, the language has ArrayBuffer and the typed arrays built on it, which store numbers of one fixed type in a contiguous block. The pieces are easy to mix up, since a buffer, a view and a Buffer all appear in the same code, and the behavior that surprises people, wrapping, sharing and byte order, follows from one idea: the buffer is memory and everything else is a lens. This post builds that picture with output from Node.js 24, covers the element types, overflow, copy versus view, DataView, resizing and strings, and ends on where an ordinary array is still the better choice. The number format behind the floating point types is in the post on how numbers work, and fill() and copyWithin() have typed-array versions covered in the copyWithin() post.

A buffer and views on it

An ArrayBuffer is a number of bytes, all zero. A typed array reads and writes it as a sequence of one numeric type.

JavaScript
const buffer = new ArrayBuffer(8);

const bytes = new Uint8Array(buffer);
const words = new Uint16Array(buffer);
const floats = new Float32Array(buffer);

bytes[0] = 1;
bytes[1] = 2;
words[1] = 513;

console.log(buffer.byteLength);
console.log(bytes.length, words.length, floats.length);
console.log(bytes);
console.log(words);
console.log(bytes.buffer === buffer, words.byteOffset, words.BYTES_PER_ELEMENT);
Text
8
8 4 2
Uint8Array(8) [
  1, 2, 1, 2,
  0, 0, 0, 0
]
Uint16Array(4) [ 513, 513, 0, 0 ]
true 0 2

The eight bytes were viewed three ways, as 8 bytes, 4 sixteen-bit words and 2 floats, with no copying. A write through one view is visible through the others: setting words[1] to 513 wrote the bytes 1 and 2 at positions 2 and 3, because 513 is 0x0201. The order they appear in, low byte first, is the platform's byte order, which is covered below. BYTES_PER_ELEMENT tells you the element size of the type.

ViewElementBytesRange
Int8ArraySigned integer1-128 to 127
Uint8ArrayUnsigned integer10 to 255
Uint8ClampedArrayUnsigned, clamped10 to 255
Int16Array, Uint16ArrayInteger216-bit
Int32Array, Uint32ArrayInteger432-bit
Float32ArrayFloating point4Single precision
Float64ArrayFloating point8Double precision, as JavaScript numbers
BigInt64Array, BigUint64ArrayBigInt864-bit integers

Writing converts and wraps

A typed array stores values of its own type. An out-of-range number does not throw. It wraps, or in the clamped type, saturates.

JavaScript
const small = new Uint8Array(4);
small[0] = 300;
small[1] = -1;
small[2] = 3.9;
small[3] = "12";

const clamped = new Uint8ClampedArray([300, -5, 3.5, 2.5]);
const signed = new Int8Array([127, 128, 255, -129]);
const single = new Float32Array([0.1, 16777217]);

console.log(small);
console.log(clamped);
console.log(signed);
console.log(single);
console.log(new Uint8Array([10, 9, 1]).sort());
console.log([10, 9, 1].sort());
Text
Uint8Array(4) [ 44, 255, 3, 12 ]
Uint8ClampedArray(4) [ 255, 0, 4, 2 ]
Int8Array(4) [ 127, -128, -1, 127 ]
Float32Array(2) [ 0.10000000149011612, 16777216 ]
Uint8Array(3) [ 1, 9, 10 ]
[ 1, 10, 9 ]

The plain unsigned array wrapped 300 to 44 and -1 to 255, truncated 3.9 to 3 and converted the string to a number. The clamped array saturated at 255 and 0, and rounded halves to even, so 2.5 became 2 and 3.5 became 4. The signed array wrapped around its range. The float array shows single precision: 0.1 is stored as the nearest 32-bit float and prints with extra digits when read back as a double, and 16777217 is above the point where 32-bit floats skip integers. Notice that typed arrays sort numerically by default, unlike plain arrays, which sort as strings.

Typed arrays cannot grow, and an out-of-range index is ignored on write and undefined on read.

JavaScript
const fixed = new Uint8Array(2);

fixed[5] = 9;
console.log(fixed, fixed[5], fixed.length);
console.log(typeof fixed.push, Array.isArray(fixed), Array.from(fixed));
console.log(fixed.map((n) => n + 1) instanceof Uint8Array);
Text
Uint8Array(2) [ 0, 0 ] undefined 2
undefined false [ 0, 0 ]
true

slice copies and subarray shares

slice() makes a new buffer, and subarray() makes a new view onto the original one. The difference decides whether an edit reaches the source.

JavaScript
const source = new Uint8Array([1, 2, 3, 4, 5, 6]);

const copy = source.slice(1, 4);
const view = source.subarray(1, 4);

copy[0] = 99;
console.log(source, copy);

view[0] = 77;
console.log(source, view);

console.log(copy.buffer === source.buffer, view.buffer === source.buffer);
console.log(view.byteOffset, view.length, view.byteLength);
Text
Uint8Array(6) [ 1, 2, 3, 4, 5, 6 ] Uint8Array(3) [ 99, 3, 4 ]
Uint8Array(6) [ 1, 77, 3, 4, 5, 6 ] Uint8Array(3) [ 77, 3, 4 ]
false true
1 3 3

Editing the copy left the source alone, and editing the view changed it. A view keeps the whole buffer alive, so a small subarray() of a huge buffer holds the entire memory, which matters for long-lived small slices. Use slice() when you need independence or want the big buffer collected. A plain array's slice() always copies, so the subarray() behavior is new to people coming from arrays.

Byte order and DataView

Typed arrays read multi-byte values in the platform's byte order, which is little-endian on the machines that run almost all JavaScript. File and network formats often specify a byte order, and a DataView reads values with an explicit one.

JavaScript
const bytes = new Uint8Array([0x12, 0x34, 0x56, 0x78]);

const view = new DataView(bytes.buffer);

console.log(view.getUint16(0, false).toString(16));
console.log(view.getUint16(0, true).toString(16));
console.log(view.getUint32(0, false).toString(16));
console.log(view.getUint32(0, true).toString(16));
console.log(new Uint16Array(bytes.buffer)[0].toString(16));

const out = new DataView(new ArrayBuffer(6));
out.setUint16(0, 0xcafe);
out.setFloat32(2, 1.5, true);

console.log([...new Uint8Array(out.buffer)].map((b) => b.toString(16).padStart(2, "0")).join(" "));
Text
1234
3412
12345678
78563412
3412
ca fe 00 00 c0 3f

The same two bytes read as 1234 in big-endian and 3412 in little-endian. The typed array read 3412, which tells us this machine is little-endian. DataView methods take a boolean littleEndian argument, false by default, so the default is big-endian, the opposite of the typed arrays. When parsing a format, such as a PNG chunk or a network header, use DataView with the order the specification names, and the code is correct on any platform.

Parsing a binary header

A small parser shows the pieces working together: read a signature, then a length and a type with a DataView.

JavaScript
const png = new Uint8Array([
  0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
  0x00, 0x00, 0x00, 0x0d,
  0x49, 0x48, 0x44, 0x52,
]);

const signature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
const isPng = signature.every((byte, i) => png[i] === byte);

const view = new DataView(png.buffer, png.byteOffset, png.byteLength);
const chunkLength = view.getUint32(8);
const chunkType = new TextDecoder().decode(png.subarray(12, 16));

console.log(isPng, chunkLength, chunkType);
Text
true 13 IHDR

The signature check compared bytes, the chunk length was read as a big-endian 32-bit integer from offset 8, and the type was decoded from four bytes as text. Passing byteOffset and byteLength to the DataView keeps the code correct when the array is itself a view into a larger buffer, a detail that causes bugs with Node.js Buffer, whose memory often comes from a shared pool.

Resizing and transferring

Since ES2024, a buffer can be created resizable and its ownership can be transferred, both available in Node.js 22 and later.

JavaScript
const growing = new ArrayBuffer(4, { maxByteLength: 16 });
const tracking = new Uint8Array(growing);

console.log(growing.resizable, growing.byteLength, tracking.length);

growing.resize(12);
console.log(growing.byteLength, tracking.length);

const moved = growing.transfer();
console.log(growing.detached, growing.byteLength, moved.byteLength);

try {
  new Uint8Array(growing);
} catch (error) {
  console.log(error.name);
}
Text
true 4 4
12 12
true 0 12
TypeError

A resizable buffer reports its current size, and a length-tracking view follows it, so the view grew from 4 to 12 with no new view. transfer() moves the contents to a new buffer and detaches the old one, which then reports zero bytes and refuses new views. This is the same operation workers use to hand memory across threads without copying, shown in the post on structuredClone().

Strings, Node.js Buffer and common conversions

TextEncoder and TextDecoder convert between strings and UTF-8 bytes. In Node.js, Buffer is a subclass of Uint8Array with extra helpers.

JavaScript
const encoded = new TextEncoder().encode("héllo");
console.log(encoded, encoded.length);
console.log(new TextDecoder().decode(encoded));

const buffer = Buffer.from("héllo");
console.log(buffer instanceof Uint8Array, buffer.toString("hex"), buffer.toString("base64"));
console.log(Buffer.from("aGk=", "base64").toString());
console.log(new Float32Array([1, 2]).buffer.byteLength, Array.from(new Uint8Array(2)));
Text
Uint8Array(6) [ 104, 195, 169, 108, 108, 111 ] 6
héllo
true 68c3a96c6c6f aMOpbGxv
hi
8 [ 0, 0 ]

The accented letter took two bytes in UTF-8, which is why byte length and string length differ, a point covered in the post on UTF-16 strings. Buffer adds hex and base64 conversion that the standard types lack, while TextEncoder works in every runtime.

A realistic use: pixels

Image data in the browser's canvas API is a Uint8ClampedArray with four bytes per pixel, red, green, blue and alpha. The clamped type is chosen so that arithmetic that overshoots saturates and does not wrap into a wrong color. A grayscale conversion shows both properties.

JavaScript
const pixels = new Uint8ClampedArray([
  255, 0, 0, 255,
  0, 255, 0, 255,
  200, 200, 250, 128,
]);

for (let i = 0; i < pixels.length; i += 4) {
  const gray = 0.299 * pixels[i] + 0.587 * pixels[i + 1] + 0.114 * pixels[i + 2];
  pixels[i] = pixels[i + 1] = pixels[i + 2] = gray * 1.5;
}

console.log([...pixels]);
Text
[
  114, 114, 114, 255,
  225, 225, 225, 255,
  255, 255, 255, 128
]

Each pixel's three color bytes became the same gray, boosted by half. The boost pushed the third pixel past 255, and the clamped array held it at 255, and it rounded the other two to whole numbers. A plain Uint8Array would have wrapped the overshoot of that third pixel to a small number and produced a dark speck where a bright one belongs. The alpha channel was never touched. The loop steps by four because the layout is interleaved, and that layout knowledge is the thing typed arrays make explicit.

Where a plain array is the better choice

Use a plain array for mixed types, for data that grows, for objects and for small collections where convenience matters. Typed arrays win for large numeric data, binary formats, graphics and audio, interop with WebAssembly and anywhere memory layout matters. We would not convert an array of a hundred numbers to a typed array on a hunch: measure first, since the conversion has a cost and the benefit is real only at scale.

Typed arrays are defined in the specification under TypedArray objects, and MDN's guide to typed arrays covers views and buffers.

Also inTypeScript
Share

Keep reading

Flat illustration of two options weighed side by side, with the TypeScript, Node.js, npm and JavaScript logos.
TypeScript

Type Annotations vs Type Assertions

A type annotation asks the compiler to check a value, while an assertion tells it to trust you. Learn the difference, the errors and safer alternatives.

6 min read
Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.