Typed Arrays and Binary Data in JavaScript

Introduction

Normal arrays can hold any type. Typed arrays (Uint8Array, Float32Array, etc.) store fixed-size numeric data in a compact binary buffer—common for files, images, WebGL, and network protocols. This chapter gives a beginner-safe overview; deep binary work often pairs with Node Buffer or browser ArrayBuffer APIs.

Prerequisites

ArrayBuffer — Raw Bytes

javascript
// 8 bytes of memory
const buffer = new ArrayBuffer(8);
console.log(buffer.byteLength);

You do not index ArrayBuffer directly—you view it through typed arrays.

Uint8Array — Bytes 0–255

javascript
// View buffer as unsigned bytes
const bytes = new Uint8Array([72, 101, 108, 108, 111]);
console.log(bytes.length);
console.log(bytes[0]);
 
// TextDecoder turns bytes into string (browser/Node)
const text = new TextDecoder().decode(bytes);
console.log(text);

Other Typed Array Types

javascript
// 32-bit floats — graphics/audio samples
const floats = new Float32Array([1.0, 2.5, 3.14]);
console.log(floats[1]);
 
// 16-bit integers
const ints = new Int16Array([-1, 0, 42]);
console.log(ints);

Common types: Int8Array, Uint16Array, Int32Array, Float64Array, BigInt64Array.

Shared Buffer, Multiple Views

javascript
// Two views on same underlying memory
const buf = new ArrayBuffer(4);
const a = new Uint8Array(buf);
const b = new Uint16Array(buf);
 
a[0] = 0xff;
a[1] = 0xff;
console.log(b[0]);

Endianness matters for cross-platform binary formats.

Node.js Buffer (Brief)

In Node, Buffer is a Uint8Array subclass for file and socket I/O:

javascript
// Node only — run with node file.js
const { Buffer } = require("buffer");
 
const buf = Buffer.from("hello", "utf8");
console.log(buf.toString("hex"));
console.log(buf.toString("utf8"));

When You Need This

  • Reading file headers or images
  • Crypto and hashing libraries
  • Web APIs (fetch + arrayBuffer())

Most app logic stays with JSON and plain arrays.

Mini Example: Simple Checksum Stub

javascript
// Sum bytes mod 256 (toy checksum, not cryptographic)
function byteSum(data) {
  let sum = 0;
  for (const byte of data) {
    sum = (sum + byte) % 256;
  }
  return sum;
}
 
const payload = new Uint8Array([10, 20, 30]);
console.log(byteSum(payload));

FAQ

Typed array vs normal array?

Typed arrays are dense numeric storage; normal arrays are flexible and object-heavy.

Can I mix types in Uint8Array?

No—only integers 0–255; out-of-range values wrap/truncate per spec rules.

DataView?

Low-level read/write of multi-byte values with explicit endianness—use when parsing binary file formats.

What comes next?

Console API.