JavaScript Typed Arrays
Working with binary data efficiently
🔢 What are Typed Arrays?
Typed Arrays provide a way to work with binary data in JavaScript. They're like regular arrays but store specific types of numbers (integers, floats) more efficiently.
// Create a typed array of 8-bit integers
const numbers = new Int8Array([1, 2, 3, 4, 5]);
console.log(numbers); // Int8Array(5) [1, 2, 3, 4, 5]
Types of Typed Arrays
Integer Arrays
Store whole numbers
Unsigned Arrays
Store positive numbers only
Float Arrays
Store decimal numbers
Special Arrays
Specialized typed arrays
🔹 Creating Typed Arrays
There are several ways to create typed arrays:
// Method 1: From length
const arr1 = new Int32Array(5); // Creates array with 5 zeros
console.log(arr1); // [0, 0, 0, 0, 0]
// Method 2: From values
const arr2 = new Int32Array([10, 20, 30]);
console.log(arr2); // [10, 20, 30]
// Method 3: From another array
const regular = [1, 2, 3, 4];
const arr3 = new Int32Array(regular);
console.log(arr3); // [1, 2, 3, 4]
Output:
Int32Array(5) [0, 0, 0, 0, 0]
Int32Array(3) [10, 20, 30]
Int32Array(4) [1, 2, 3, 4]
🔹 Working with Typed Arrays
Typed arrays work similarly to regular arrays:
const numbers = new Uint8Array([10, 20, 30, 40, 50]);
// Access elements
console.log(numbers[0]); // 10
console.log(numbers[2]); // 30
// Modify elements
numbers[1] = 25;
console.log(numbers); // [10, 25, 30, 40, 50]
// Get length
console.log(numbers.length); // 5
// Loop through array
for (let i = 0; i < numbers.length; i++) {
console.log(`Index ${i}: ${numbers[i]}`);
}
Output:
10
30
Uint8Array(5) [10, 25, 30, 40, 50]
5
Index 0: 10
Index 1: 25
Index 2: 30
Index 3: 40
Index 4: 50
🔹 Practical Example
Here's a practical example using typed arrays for image data:
// Simulate RGB pixel data (Red, Green, Blue values)
const imageData = new Uint8Array([
255, 0, 0, // Red pixel
0, 255, 0, // Green pixel
0, 0, 255, // Blue pixel
255, 255, 0 // Yellow pixel
]);
// Process the image data
function processPixels(data) {
const pixels = [];
for (let i = 0; i < data.length; i += 3) {
const red = data[i];
const green = data[i + 1];
const blue = data[i + 2];
pixels.push(`RGB(${red}, ${green}, ${blue})`);
}
return pixels;
}
const pixels = processPixels(imageData);
console.log(pixels);
Output:
["RGB(255, 0, 0)", "RGB(0, 255, 0)", "RGB(0, 0, 255)", "RGB(255, 255, 0)"]