Mastering JavaScript Binary Data: ArrayBuffer, TypedArray & DataView Explained
This guide introduces JavaScript’s low‑level binary data tools—ArrayBuffer, TypedArrays, and DataView—explaining their concepts, creation methods, key properties, and performance considerations, and demonstrates practical applications such as image processing, audio analysis, and WebSocket binary protocols.
In web development, JSON is often used for data exchange, but binary handling is needed for images, video, or socket communication. JavaScript provides powerful tools—ArrayBuffer, TypedArrays, and DataView—to manage raw binary data efficiently.
ArrayBuffer Basics
What Is ArrayBuffer?
ArrayBuffer represents a generic, fixed‑length raw binary data buffer, similar to a byte array in other languages. It cannot be accessed directly; a view such as a TypedArray or DataView is required.
<code>// Create an 8‑byte (64‑bit) ArrayBuffer
let buffer = new ArrayBuffer(8);
// Check the buffer length
console.log(buffer.byteLength); // 8</code>Creating an ArrayBuffer
Use the ArrayBuffer constructor with the desired byte length.
<code>let buffer = new ArrayBuffer(16);</code>Main Property and Method
byteLength : read‑only length in bytes.
slice : returns a new ArrayBuffer containing a copy of a portion of the original.
<code>let buffer = new ArrayBuffer(8);
let newBuffer = buffer.slice(2, 6);</code>TypedArrays Overview
What Are TypedArrays?
TypedArrays are type‑specific views of an ArrayBuffer, allowing native handling of binary data. Common types include Int8Array , Uint8Array , Int16Array , Uint16Array , Int32Array , Uint32Array , Float32Array , and Float64Array .
<code>let buffer = new ArrayBuffer(16);
let int32View = new Int32Array(buffer);
int32View[0] = 42;
console.log(int32View[0]); // 42</code>Common TypedArray Types and Ranges
Int8Array : -128 to 127
Uint8Array : 0 to 255
Uint8ClampedArray : 0 to 255 (clamped)
Int16Array : -32,768 to 32,767
Uint16Array : 0 to 65,535
Int32Array : -2,147,483,648 to 2,147,483,647
Uint32Array : 0 to 4,294,967,295
Float32Array : 1.2e‑38 to 3.4e38 (single precision)
Float64Array : 5.0e‑324 to 1.8e308 (double precision)
Creating TypedArrays and Their Methods
<code>let buffer = new ArrayBuffer(16);
let float32View = new Float32Array(buffer);
</code>Key properties and methods:
length : number of elements.
set : copy values from an array or another TypedArray.
subarray : create a view over a subset of the buffer.
<code>let buffer = new ArrayBuffer(16);
let int16View = new Int16Array(buffer);
int16View.set([1, 2, 3]);
let sub = int16View.subarray(1, 3);
console.log(sub); // Int16Array(2) [2, 3]
</code>TypedArrays vs. Regular Arrays
TypedArrays store raw binary data; regular arrays store JavaScript objects.
Elements have fixed size and are stored in contiguous memory, offering higher performance.
DataView Detailed Analysis
What Is DataView?
DataView provides a flexible view over an ArrayBuffer, allowing read/write of various numeric types with explicit byte offsets and endianness.
<code>let buffer = new ArrayBuffer(16);
let view = new DataView(buffer);
view.setInt8(1, 42);
console.log(view.getInt8(1)); // 42
</code>Creating a DataView
Pass an ArrayBuffer and optionally specify byte offset and length.
<code>let buffer = new ArrayBuffer(16);
let view = new DataView(buffer, 4, 8); // start at byte 4, length 8
</code>Key Methods and Properties
getInt8 / setInt8 : 8‑bit signed integer.
getUint8 / setUint8 : 8‑bit unsigned integer.
getInt16 / setInt16 : 16‑bit signed integer.
getUint16 / setUint16 : 16‑bit unsigned integer.
getInt32 / setInt32 : 32‑bit signed integer.
getUint32 / setUint32 : 32‑bit unsigned integer.
getFloat32 / setFloat32 : 32‑bit float.
getFloat64 / setFloat64 : 64‑bit float.
<code>let buffer = new ArrayBuffer(16);
let view = new DataView(buffer);
view.setFloat32(0, 3.14);
console.log(view.getFloat32(0)); // 3.140000104904175
</code>Using DataView for Mixed‑Type Data
<code>let buffer = new ArrayBuffer(16);
let view = new DataView(buffer);
view.setInt8(0, 32);
view.setFloat32(1, 3.14);
console.log(view.getInt8(0)); // 32
console.log(view.getFloat32(1)); // 3.140000104904175
</code>Practical Applications and Examples
Image Processing
<code>// Get uploaded image data
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
let img = document.getElementById('uploadedImage');
canvas.width = img.width;
canvas.height = img.height;
context.drawImage(img, 0, 0);
// Extract pixel data
let imageData = context.getImageData(0, 0, canvas.width, canvas.height);
let buffer = imageData.data.buffer; // ArrayBuffer
let uint8View = new Uint8ClampedArray(buffer);
// Apply grayscale filter
for (let i = 0; i < uint8View.length; i += 4) {
let avg = (uint8View[i] + uint8View[i+1] + uint8View[i+2]) / 3;
uint8View[i] = avg; // R
uint8View[i+1] = avg; // G
uint8View[i+2] = avg; // B
}
// Update canvas
context.putImageData(imageData, 0, 0);
</code>Audio Processing
<code>navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
let audioContext = new (window.AudioContext || window.webkitAudioContext)();
let analyser = audioContext.createAnalyser();
let source = audioContext.createMediaStreamSource(stream);
source.connect(analyser);
analyser.fftSize = 2048;
let bufferLength = analyser.frequencyBinCount;
let dataArray = new Uint8Array(bufferLength);
function draw() {
requestAnimationFrame(draw);
analyser.getByteFrequencyData(dataArray);
// renderFrequencyData(dataArray);
}
draw();
});
</code>Network Protocol Parsing
<code>let socket = new WebSocket('wss://stock-data.example.com');
socket.binaryType = 'arraybuffer';
socket.onmessage = function(event) {
let buffer = event.data;
let dataView = new DataView(buffer);
// Assume packet format: [stockCode(4 bytes), price(4 bytes), volume(4 bytes)]
let stockCode = dataView.getUint32(0);
let price = dataView.getFloat32(4);
let volume = dataView.getUint32(8);
// updateStockInfo(stockCode, price, volume);
};
</code>Choosing the right tool depends on the scenario: use TypedArrays for homogeneous data, and DataView when handling multiple data types within the same buffer. Beware of byte‑order issues and selecting inappropriate data types, which can lead to errors or performance loss.
Code Mala Tang
Read source code together, write articles together, and enjoy spicy hot pot together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.