TypedArrays & ArrayBuffers
TypedArrays & ArrayBuffers in Modern JavaScript
Standard JavaScript arrays are dynamic, hash-like objects capable of holding heterogeneous types. While flexible, they carry substantial memory overhead and cannot directly interface with raw binary hardware protocols, WebGL shaders, audio streams, or WebAssembly. ArrayBuffer and TypedArrays provide fast, fixed-size, low-level binary memory management.
1. ArrayBuffer: The Raw Memory Slab
An ArrayBuffer represents a fixed-length contiguous block of raw binary memory:
ArrayBuffer directly! You must access it through a View—either a TypedArray or a DataView.2. TypedArray Views
A TypedArray interprets the underlying buffer as an array of elements of a specific numerical type:
| TypedArray | Element Type | Bytes per Element | Value Range |
|---|---|---|---|
Int8Array | 8-bit Signed Int | 1 | -128 to 127 |
Uint8Array | 8-bit Unsigned Int | 1 | 0 to 255 |
Uint8ClampedArray | 8-bit Clamped Int | 1 | 0 to 255 (Clamps overflow, Canvas/Image data) |
Int16Array | 16-bit Signed Int | 2 | -32,768 to 32,767 |
Int32Array | 32-bit Signed Int | 4 | -2,147,483,648 to 2,147,483,647 |
Float32Array | 32-bit Float | 4 | IEEE 754 floating point (WebGL vectors) |
Float64Array | 64-bit Float | 8 | Standard JS Number precision |
3. DataView & Endianness (Byte Ordering)
When parsing binary file formats (e.g. PNG headers, MP3 tags) or network packets, different systems store multi-byte numbers in different byte orders (Big-Endian vs Little-Endian). DataView allows heterogeneous reading/writing with explicit endianness control:
4. Subarray vs. Slice (Zero-Copy Sharing)
typedArray.subarray(start, end): Creates a new TypedArray view sharing the exact same memory buffer (Zero copy!).typedArray.slice(start, end): Creates a deep copy with a newly allocated buffer.
Practice Quiz
WeakMap & WeakSet for Memory Management
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Proxy & Decorator Patterns | WeakMap & WeakSet for Memory Management |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.