Typed arrays: ArrayBuffer and byte views

A typed array is an array of numbers of one element type, laid out in memory and reached through an ArrayBuffer. It has a fixed length, no methods that change that length, and a value that wraps at the edge of its type. It exists for the places where an ordinary JavaScript array is the wrong shape: the bytes of a file, a network packet, an image, or a buffer for reading a file from disk.

This lesson covers the buffer and its first view, the overflow that a byte does instead of an error, the several views a single buffer can have, and the conversion of text to bytes and back. The arrays of the first lesson of this part stay the tool for a list of values.

An ArrayBuffer is bytes

new ArrayBuffer(4) reserves four bytes and says nothing about how they are read. A view does the reading: new Uint8Array(buffer) is an array of four unsigned numbers, one per byte, and a write to a view changes the buffer. The program writes one byte and reads it back through a second view.

const buffer = new ArrayBuffer(4); console.log('byte length:', buffer.byteLength); const bytes = new Uint8Array(buffer); console.log('a view starts at zero:', bytes.length, [...bytes].join(',')); bytes[0] = 255; console.log('one element:', bytes[0]); console.log('the buffer is the storage:', new Uint8Array(buffer)[0]); const fromArray = new Uint8Array([1, 2, 3]); console.log('from an array:', fromArray.length, [...fromArray].join(',')); console.log('a typed array is not an array:', Array.isArray(fromArray));

node buffer.js

byte length: 4
a view starts at zero: 4 0,0,0,0
one element: 255
the buffer is the storage: 255
from an array: 3 1,2,3
a typed array is not an array: false

A new buffer is filled with zero bytes, which the second line shows through the view. The write to the first byte was visible through a second view of the same buffer, because a view holds no data of its own. The last two lines are the other way to make one: a typed array given an array copies its numbers, and the result is still not an Array, so push and splice are not there.

Overflow and the element type

A typed array stores values of one type and has no room to store anything else, so a value that does not fit is wrapped rather than refused: the number is taken modulo the range of the type and the low bits are kept. A byte holds 256 values, so 256 becomes 0, 300 becomes 44, and -1 becomes 255. A signed byte reaches from -128 to 127, and 200 becomes -56.

console.log('256 in a byte:', Uint8Array.of(256)[0]); console.log('300 in a byte:', Uint8Array.of(300)[0]); console.log('-1 in a byte:', Uint8Array.of(-1)[0]); console.log('1.9 in a byte:', Uint8Array.of(1.9)[0]); const bytes = new Uint8Array(1); bytes[0] = 255; bytes[0] += 1; console.log('the byte after 255:', bytes[0]); console.log('200 in a signed byte:', Int8Array.of(200)[0]); console.log('70000 in 16 bits:', Uint16Array.of(70000)[0]);

node overflow.js

256 in a byte: 0
300 in a byte: 44
-1 in a byte: 255
1.9 in a byte: 1
the byte after 255: 0
200 in a signed byte: -56
70000 in 16 bits: 4464

Nothing here throws, and that is the property to know: the type of the element decides the range and the value is cut to fit. Adding one to 255 gave 0, which is a counter that wraps in a program that expected an error. The fraction 1.9 was truncated to 1, the signed byte took 200 as -56, and the 16-bit type held 4464 where the number was 70000. A program that reads binary data has to know the type it asked for, since the wrap is silent.

Several views of one buffer

A view can start at an offset and cover part of a buffer, and byteOffset and length say where it is and how much it covers. That is how a layout is read: a header in the first bytes and the data after it, with one view for each part. A DataView is the other reader, one value of a chosen type at a chosen place.

const buffer = new ArrayBuffer(8); const all = new Uint8Array(buffer); const head = new Uint8Array(buffer, 0, 4); const tail = new Uint8Array(buffer, 4, 4); head[0] = 1; tail[0] = 2; all[7] = 255; console.log('the whole buffer:', [...all].join(',')); console.log('where the head starts:', head.byteOffset, 'and the tail:', tail.byteOffset); console.log('each view has its own length:', head.length, tail.length); console.log('a write through the whole view:', tail[3]); const view = new DataView(buffer); console.log('one byte at a time:', view.getUint8(0), view.getUint8(4), view.getUint8(7)); view.setUint8(0, 9); console.log('a write through the DataView:', all[0]);

node views.js

the whole buffer: 1,0,0,0,2,0,0,255
where the head starts: 0 and the tail: 4
each view has its own length: 4 4
a write through the whole view: 255
one byte at a time: 1 2 255
a write through the DataView: 9

Three views, one buffer: the first wrote at its own index 0, which is byte 0, the second at its index 0, which is byte 4, and the third at byte 7. The tail read the 255 that the whole view wrote at byte 7, because a view has no storage and only an address. The DataView read the same three bytes one by one and then wrote one, which the first view saw; it takes an offset and a method instead of an index, so it is the reader for a format whose fields are not all single bytes.

Text and bytes

Text becomes bytes with TextEncoder, which writes UTF-8, and comes back with TextDecoder. UTF-8 uses one byte for the letters of ASCII and more for the rest, so a character such as é takes two and an emoji takes four. The program encodes a word, prints the bytes and decodes them again.

const text = 'héllo'; const encoded = new TextEncoder().encode(text); console.log('bytes:', encoded.length); console.log('the values:', [...encoded].join(',')); console.log('back to text:', new TextDecoder().decode(encoded)); console.log('from two bytes:', new TextDecoder().decode(new Uint8Array([0x68, 0x69]))); try { encoded.push(1); } catch (error) { console.log(error.name + ': ' + error.message); }

node bytes.js

bytes: 6
the values: 104,195,169,108,108,111
back to text: héllo
from two bytes: hi
TypeError: encoded.push is not a function

Five letters took six bytes, because é is 195 and 169 and the other four letters are one byte each. The decoder turned the same six bytes back into the same word, and the two bytes written as hexadecimal read as hi, so the round trip is the whole conversion. The last line is the fixed length in practice: a typed array has no push, and a program that reads more bytes than it reserved makes a larger buffer instead.

Exercises

  1. Change new ArrayBuffer(4) in buffer.js to 8. Which line of the output changes, and what do the new bytes hold?
  2. Store 511 in a Uint8Array and in a Uint16Array. Which of the two holds the number, and what does the other one keep?
  3. Give the tail view in views.js an offset of 2 and a length of 2. Which bytes does it cover, and what does all[4] show after tail[0] = 7?
  4. Encode an emoji with TextEncoder and print the length of the result and its values. How many bytes does it take?
  5. Read the buffer of views.js with getUint16(6) and then with getUint16(7). Which of the two throws, and why?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is an ArrayBuffer?

    Answer

    A block of bytes that a view reads and writes

    The buffer holds the bytes and says nothing about their type; a view gives them a type and an index.

  2. What does Uint8Array.of(256)[0] give?

    Answer

    0

    A byte holds 256 values from 0 to 255, and 256 wraps to 0 without an error.

  3. What does Uint8Array.of(-1)[0] give?

    Answer

    255

    An unsigned byte keeps the low eight bits, and -1 in two-complement form is 255 there.

  4. What does Int8Array.of(200)[0] give?

    Answer

    -56

    A signed byte reaches from -128 to 127, and 200 wraps to -56.

  5. What does this program print? const b = new Uint8Array(2); console.log(b.length, b[0]);

    Answer

    2 0

    A new buffer is filled with zero bytes, which a typed array reads as the number 0.

  6. What does this program print? const b = new Uint8Array(2); b[0] = 255; b[0] += 1; console.log(b[0]);

    Answer

    0

    The byte wraps at its type, so 256 is stored as 0.

  7. What does byteOffset say about a view?

    Answer

    The position of its first element in the buffer

    It is the address of the view, which is why two views can start at different places.

  8. What happens when two views cover the same buffer?

    Answer

    A write through one view is visible through the other

    A view has no storage of its own, so both read and write the same bytes.

  9. What does this program print? console.log(new TextEncoder().encode("hi").length);

    Answer

    2

    Both letters are ASCII, and UTF-8 writes each of them as one byte.

  10. Why does a typed array have no push?

    Answer

    Its length is fixed by the buffer it reads

    The buffer has a fixed size, so a program that needs more room makes a larger buffer instead.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image