Skip to content
Tutorials Center
My learning

Topics

Lesson 118 of 156 ยท Built-in Tools

Typed Arrays and Binary Data

Work with raw bytes in JavaScript - ArrayBuffer, Uint8Array and other typed arrays, DataView, endianness, TextEncoder, and SharedArrayBuffer basics.

Most JavaScript data is high-level: strings, numbers, objects. But sooner or later you'll need the bytes underneath. Image pixels, audio samples, file headers, network protocols, WebGL buffers, compression and cryptography all deal in raw binary data. A regular array is a poor fit for that job: each element can be any type, and a number always takes 8 bytes.

Typed arrays solve this. They give you fixed-size, fixed-type views over a block of memory, so you can read and write individual bytes, 16-bit integers or 32-bit floats quickly and predictably. In this lesson you'll learn how ArrayBuffer, typed arrays and DataView fit together, why byte order matters, how to turn text into bytes and back, and what SharedArrayBuffer is for.

ArrayBuffer: a block of raw memory

An ArrayBuffer is a fixed-length chunk of bytes, all starting at zero. On its own it can't do much โ€” it has no methods for reading or writing individual bytes. Think of it as a sealed box of memory.

JavaScript
const buffer = new ArrayBuffer(8); // 8 bytes, all 0
buffer.byteLength;                 // 8

To look inside, you create a view over it. There are two kinds of views:

  • Typed arrays (Uint8Array, Int16Array, Float64Array and friends) treat the bytes as a list of numbers that all have the same type.
  • DataView lets you read and write any type at any byte offset, and choose the byte order each time.

Several views can share the same buffer. Writing through one view changes what the others see, because there's only one block of memory.

The typed array family

Each typed array type fixes the size and kind of every element:

Type Bytes per element Range
Int8Array / Uint8Array 1 โˆ’128โ€ฆ127 / 0โ€ฆ255
Uint8ClampedArray 1 0โ€ฆ255, clamped instead of wrapped
Int16Array / Uint16Array 2 โˆ’32,768โ€ฆ32,767 / 0โ€ฆ65,535
Int32Array / Uint32Array 4 about ยฑ2.1 billion / 0โ€ฆ4.29 billion
Float32Array / Float64Array 4 / 8 single / double precision decimals
BigInt64Array / BigUint64Array 8 64-bit integers as BigInt

There is also Float16Array (2 bytes per element), added in ES2025 and now supported in current browsers; it's popular for machine learning and graphics data.

Typed arrays have most of the array methods you know โ€” map(), filter(), reduce(), includes(), sort(), at(), iteration with for...of โ€” but they can't grow or shrink. There's no push() or pop(). Values that don't fit are converted: integers wrap around, decimals are cut off, and only Uint8ClampedArray clamps to the nearest edge instead.

JS Typed arrays and overflow

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that 23.1 comes back as something like 23.100000381469727. A Float32Array stores less precision than a normal JavaScript number, so decimals get rounded to the nearest value a 32-bit float can hold.

Many views, one buffer

When you create a typed array with a length, it creates its own buffer behind the scenes (available as .buffer). You can also pass an existing buffer, optionally with a byte offset and a length, to view just part of it.

This is where the "view" idea becomes powerful. Below, the same 8 bytes are seen as bytes, as 16-bit numbers and as one 32-bit number:

JS Views sharing one buffer

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Two details to remember:

  • subarray() returns a new view over the same memory; slice() returns a copy. Mixing them up is a common source of "why did my data change?" bugs.
  • A multi-byte view must start at a multiple of its element size. new Uint32Array(buffer, 3) throws a RangeError because 3 isn't divisible by 4. Use DataView when your data isn't aligned.

Endianness and DataView

Look again at the Uint16Array result above: bytes [1, 1] became 257, and bytes [1, 0] would be 1. Which byte counts as the "big" one? That's called endianness:

  • Little-endian: the least significant byte comes first. Almost every modern CPU (x86, ARM in its normal mode) works this way, so typed arrays usually do too.
  • Big-endian: the most significant byte comes first, the way we write numbers. Many file formats and network protocols ("network byte order") use it.

Typed arrays always use the computer's native order, which you can't choose. That's fine for data that stays on one machine, but file formats and protocols specify a byte order, and your code must follow it. DataView handles this: every getter and setter takes a byte offset and an optional littleEndian flag (big-endian is the default).

JS Reading a binary header with DataView

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Rule of thumb: use a typed array when all your data has one type and stays in native order (pixels, audio samples, vertex lists). Use DataView for structured records with mixed types, odd offsets or a fixed byte order (file headers, protocol messages).

The full DataView toolbox

DataView has a pair of methods for every number type, named get and set plus the type name. Both take a byte offset (not an element index), and the setters take the value as the second argument. For types wider than one byte, the last argument is littleEndian, which defaults to false (big-endian):

Type Getter / setter Size
Signed / unsigned 8-bit getInt8, getUint8 1 byte (no endianness flag)
Signed / unsigned 16-bit getInt16, getUint16 2 bytes
Signed / unsigned 32-bit getInt32, getUint32 4 bytes
32 / 64-bit floating point getFloat32, getFloat64 4 / 8 bytes
Signed / unsigned 64-bit getBigInt64, getBigUint64 8 bytes, values are BigInt

(Newer engines also have getFloat16 for 16-bit floats; check support before using it.) A view can cover part of a buffer: new DataView(buffer, byteOffset, byteLength). Reading or writing past the end throws a RangeError instead of corrupting memory, which makes DataView a safe choice for parsing untrusted files.

JS Every number type in one buffer

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the 64-bit values: JavaScript numbers lose exact precision above 2^53, so these methods use BigInt instead. A Float32Array or getFloat32() also rounds, so 1.1 read back from a float32 is 1.100000023841858.

Text to bytes and back

Strings aren't bytes. To store text in a buffer you must encode it, and the web's standard encoding is UTF-8, where English letters take 1 byte and other characters take 2โ€“4. Two built-in classes do the work:

  • new TextEncoder().encode(string) returns a Uint8Array of UTF-8 bytes.
  • new TextDecoder().decode(bytes) turns bytes back into a string. It accepts other encodings too, such as new TextDecoder("utf-16le").
JS TextEncoder and TextDecoder

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Note how "cafรฉ".length is 4 but it takes 5 bytes, and the fox emoji has a string length of 2 (two UTF-16 code units) but 4 bytes. Never assume one character equals one byte.

Where binary data comes from

You'll rarely build buffers by hand. Browser APIs hand them to you:

JavaScript
const response = await fetch("/photo.png");
const bytes = new Uint8Array(await response.arrayBuffer());

const file = input.files[0];             // from <input type="file">
const fileBytes = await file.bytes();    // Uint8Array (newer; or new Uint8Array(await file.arrayBuffer()))

const random = crypto.getRandomValues(new Uint8Array(16)); // secure random bytes
const pixels = ctx.getImageData(0, 0, w, h).data;          // Uint8ClampedArray, RGBA

Files, Blobs and Base64 covers reading files and converting bytes to Base64 text.

Growing buffers

A classic ArrayBuffer has a fixed size forever. Since ES2024 you can create a resizable buffer by giving it a maximum size, and views created without a fixed length grow with it:

JavaScript
const buf = new ArrayBuffer(4, { maxByteLength: 64 });
const view = new Uint8Array(buf);   // length tracks the buffer
buf.resize(16);
view.length;                        // 16

buffer.transfer() (also ES2024) moves the memory into a new buffer and detaches the old one, which then has a byteLength of 0. Transferring is also how you hand a buffer to a Web Worker with postMessage(buf, [buf]) without copying it โ€” see JavaScript Performance.

Resizable buffers in detail

A resizable buffer is created with new ArrayBuffer(initialBytes, { maxByteLength }). The maximum is a hard ceiling: the engine reserves room for it, but only byteLength bytes are in use. You change the size with buffer.resize(newByteLength); growing fills the new bytes with zeros, shrinking discards bytes from the end, and any size above maxByteLength throws a RangeError. Two properties tell you what you have: buffer.resizable and buffer.maxByteLength.

How a view reacts depends on how you created it:

  • Length-tracking view (no length given, such as new Uint8Array(buffer) or new Uint8Array(buffer, 4)): its length follows the buffer automatically.
  • Fixed-length view (a length given, such as new Uint8Array(buffer, 0, 4)): keeps its size, but if the buffer shrinks below the end of the view, the view becomes out of bounds and reports length 0 (and byteOffset 0) until the buffer grows again. Reading it gives undefined and doesn't throw.
JS Resizing a buffer under three views

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Use resizable buffers for append-only byte data such as a network read buffer, a recorded audio stream or a file being built in memory: you avoid allocating a bigger buffer and copying every time you run out of room. transfer() is also the cheap way to "shrink to fit" once you know the final size, and detached lets you check whether a buffer has been given away.

SharedArrayBuffer and Atomics

A normal ArrayBuffer belongs to one thread. When you send it to a Web Worker it's either copied or transferred, but never shared. A SharedArrayBuffer is different: the main thread and several workers can all view the same memory at once. That makes heavy parallel work (video encoding, physics, emulators, compiled WebAssembly apps) possible.

Shared memory brings a classic problem: two threads changing the same value at the same moment can lose updates. The Atomics object provides operations that can't be interrupted halfway:

JavaScript
// main.js
const shared = new SharedArrayBuffer(4);
const counter = new Int32Array(shared);
worker.postMessage(shared);        // the worker views the same memory

// in each worker
Atomics.add(counter, 0, 1);        // safe increment, even from many threads
Atomics.load(counter, 0);          // safe read
Atomics.wait(counter, 0, 0);       // sleep until the value changes (workers only)
Atomics.notify(counter, 0);        // wake waiting threads

Availability: after the 2018 Spectre CPU attacks, browsers only provide SharedArrayBuffer on cross-origin isolated pages, which must be served with the Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp headers. Check self.crossOriginIsolated before using it. Our live editors aren't cross-origin isolated, so this part is read-only.

Most apps never need shared memory. Message passing with postMessage is simpler and safer; reach for SharedArrayBuffer only when copying data between threads becomes the bottleneck.

The Atomics operations

Atomics is a namespace of static functions. Each one takes an integer typed array (Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array or BigUint64Array; floats are rejected), an index, and usually a value. The read-modify-write functions all return the old value:

Function What it does
Atomics.load(a, i) / Atomics.store(a, i, v) Read / write one element; store returns the value stored
Atomics.add, sub, and, or, xor Apply the operation and return the previous value
Atomics.exchange(a, i, v) Store v and return the previous value
Atomics.compareExchange(a, i, expected, v) Store v only if the current value equals expected; always returns the previous value
Atomics.isLockFree(bytes) Reports whether operations on that element size avoid locks (4 always does)
Atomics.wait, notify Sleep until woken / wake sleepers; only for SharedArrayBuffer-backed arrays

You don't need threads to try the first group. They work on ordinary typed arrays too, which is a good way to learn what they return. compareExchange is the building block for lock-free algorithms: "set it to the new value, but only if nobody changed it since I looked." Retrying in a loop until it succeeds is called a compare-and-swap (CAS) loop:

JS Atomics operations and a CAS loop

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Why bother, if a single thread can't be interrupted halfway through a[0]++? Because with a SharedArrayBuffer, another thread can run between the read and the write of a[0]++ and one of the two updates is lost. Atomics.add() does the whole read-modify-write as one step. The blocking functions are the read-only part of this lesson:

JavaScript
// In a worker, with an Int32Array on a SharedArrayBuffer
Atomics.wait(flag, 0, 0, 1000);   // sleep while flag[0] is 0, at most 1000 ms
// Returns "ok" (woken), "not-equal" (value was not 0) or "timed-out"

// In another thread
Atomics.store(flag, 0, 1);
Atomics.notify(flag, 0, 1);       // wake one waiter; returns how many woke up

Atomics.wait() blocks the thread, so browsers forbid it on the main thread (it throws); use it only inside workers, and use Atomics.waitAsync() where you need a non-blocking wait. On an array whose buffer is not shared, wait throws a TypeError as well.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does new Uint8Array([260])[0] contain?

    Integer typed arrays wrap around. 260 doesn't fit in 0โ€“255, so it becomes 260 โˆ’ 256 = 4. Only Uint8ClampedArray would clamp to 255.
  2. 2. What is the difference between subarray() and slice() on a typed array?

    subarray() creates another view over the same buffer, so writes show up in both. slice() creates a new buffer with copied data.
  3. 3. When should you use a DataView instead of a typed array?

    DataView reads any type at any offset and lets you choose little- or big-endian per call, which matches how file formats and protocols are specified.
  4. 4. How many bytes does new TextEncoder().encode("cafรฉ") produce?

    UTF-8 uses 1 byte for c, a and f, and 2 bytes for รฉ, giving 5 bytes even though the string length is 4.
  5. 5. Why might SharedArrayBuffer be unavailable on a page?

    Browsers require cross-origin isolation for shared memory as a Spectre mitigation. self.crossOriginIsolated tells you whether it's on.

Summary

  • An ArrayBuffer is raw memory; you read and write it through views.
  • Typed arrays (Uint8Array, Int16Array, Float32Arrayโ€ฆ) have a fixed length and element type; integers wrap, Uint8ClampedArray clamps.
  • Many views can share one buffer. subarray() shares memory, slice() copies.
  • Byte order matters for files and protocols: use DataView with its littleEndian flag.
  • TextEncoder and TextDecoder convert between strings and UTF-8 bytes; characters can take 1โ€“4 bytes.
  • DataView has a getter and setter per number type (including BigInt 64-bit ones) and throws a RangeError when you go out of bounds.
  • Resizable buffers (maxByteLength, resize()) keep length-tracking views in step; fixed-length views go out of bounds when the buffer shrinks. transfer() moves the bytes and detaches the old buffer. Both arrived in ES2024.
  • Atomics operations (add, compareExchange, exchange, and/or/xor...) work on integer typed arrays and return the old value; wait and notify need a SharedArrayBuffer and a worker.
  • SharedArrayBuffer plus Atomics share memory between threads, but only on cross-origin isolated pages.

Next: Memory Management and Garbage Collection โ€” see where values live, how JavaScript frees them, and how leaks happen.