bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/JavaScript/Objects, Classes, and Advanced Patterns
JavaScript•Objects, Classes, and Advanced Patterns

JavaScript Typed Arrays

Concept visual

JavaScript Typed Arrays

Graph traversalgraph
ABCDE
current
queued
1
4

Start from A

Typed Arrays

Typed arrays was designed for handling

Binary Data. Unlike arrays, typed arrays are buffers of Fixed Length.

Typed arrays store elements of

Formula

Fixed Types like 8 - bit integers or 32 - bit numbers.

Examples

Create a typed array of 5 bytes:

const myArr = new Uint8Array(5);

Create a typed array from an array:

const myArr = new Uint8Array([0,1,2,3,4]);

Create a typed array from a list of numbers:

const myArr = Uint8Array.of(0,1,2,3,4);

Create a typed array from an array:

const myArr = Uint8Array.from([0,1,2,3,4]);

Typed Array Benefits

Typed Arrays were designed to provide an efficient way to handle binary data, unlike traditional JavaScript arrays which can hold elements of mixed data types. Typed arrays are raw memory, so JavaScript can pass them directly to any function without converting the data to another representation. Typed arrays are seriously faster than normal arrays for passing data to functions that can use raw binary data. Typed Arrays are highly suitable for:

WebGL and Canvas

Fast graphics rendering and image processing.

File APIs

Fast reading and writing of local files.

Media APIs

Fast handling of audio and video data.

WebSockets

Efficient binary data transfer over network. Typed arrays provide a way to handle binary data as efficiently as arrays work in C.

Browser APIs Supporting Typed Arrays

Fetch API Example fetch(url).then(request => request.arrayBuffer()).then(arrayBuffer =>...);

Canvas Example

const canvas = document.getElementById('my_canvas');
const context = canvas.getContext('2d');
const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
const uint8ClampedArray = imageData.data;

Differences from Regular Arrays

Fixed Length:

Typed Arrays cannot be dynamically resized using methods like push() or pop().

Type Restriction:

Elements must adhere to the specified data type of the typed array.

Underlying Buffer:

Typed Arrays are views into an ArrayBuffer, allowing direct manipulation of binary data.

Typed Array Types

Name

Min

Max

Bytes

Type

Int8Array

-128 127

byte

Uint8Array

255

octet

Uint8ClampedArray

255

octet

Previous

Reflect & Proxy Reference

Next

Typed Array Methods