liveBook · Manning

Typed array

As explained in Secrets of the JavaScript Ninja, Third Edition

A typed array is a JavaScript array-like data structure that stores elements of a specified numeric type in a raw binary representation.

When bytes encode an image or other binary data, a typed array lets you interpret and access them as values of a specified numeric type. Unlike ordinary JavaScript arrays, its elements share a type; a Uint8Array, for example, represents bytes as unsigned 8-bit integers from 0 to 255. Typed arrays provide a way to read and write buffer data, and each has an underlying buffer. section 11.1.2 section 10.1

Listing 11.2 Constructing a buffer using typed arrays
// Create an image header for a PNG file
const chunkLength = new Uint8Array([0, 0, 0, 13]); #A
const chunkType = new TextEncoder().encode("IHDR"); #B
const ihdrData = new Uint8Array(13); #C
ihdrData[8] = 8; #C
ihdrData[9] = 6; #C
const dummyCrc = new Uint8Array(4); #D

const ihdrChunk = new Uint8Array([ #E
  ...chunkLength, #E
  ...chunkType, #E
  ...ihdrData, #E
  ...dummyCrc, #E
]);

console.assert(
  ihdrChunk[16] === 8,
  "Bit depth is 8"
);
console.assert(
  ihdrChunk[17] === 6,
  "Color type 6 means RGBA"
);

const type = String.fromCharCode(
  ...ihdrChunk.subarray(4, 8)
);
console.assert(type === "IHDR", "Chunk type is IHDR");

This example assembles a PNG header from typed-array chunks, then checks selected byte values and reads the chunk type. section 11.1.2

Node.js Buffer inherits from Uint8Array, so a Buffer can be accessed like an array of bytes. Typed arrays are not ordinary JavaScript arrays: Array.isArray(new Uint8Array()) returns false. Use them when code needs to interpret or construct raw numeric data; their underlying buffer may also be shared with other objects. section 11.1.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains numeric element types, buffer relationships, and byte access through a PNG-header example.
Examples
Uses a PNG header, a Buffer containing “Hello,” and an Array.isArray check to demonstrate typed-array behavior.
What you can do after
Build it from scratch by assembling a PNG header from typed-array chunks, with a proper CRC left aside.
How it connects
Connects typed arrays to buffers, DataView, encoders, decoders, and ordinary JavaScript arrays.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.