Course contentsShow
← JavaScript
Lesson 2327 of 2,72348. Working with Binary DataFree lesson

Typed Array Methods: Set and Subarray

Copying data efficiently with set() and creating views with subarray().

Typed Array Methods: Set and Subarray

You'll learn how to efficiently copy data between typed arrays and create lightweight views into existing data.

Core Concept

Typed arrays provide two powerful methods for working with binary data without unnecessary copying. The set() method copies elements from one array into another at a specified position, while subarray() creates a view into the same underlying buffer—no data duplication involved.

The set() Method

Think of set() like pouring one container into another at a specific starting point:

const target = new Uint8Array(10);
const source = new Uint8Array([1, 2, 3, 4]);

target.set(source, 2); // Copy source into target starting at index 2
// target is now: [0, 0, 1, 2, 3, 4, 0, 0, 0, 0]

You can also copy from regular arrays:

target.set([99, 88], 0);
// target is now: [99, 88, 1, 2, 3, 4, 0, 0, 0, 0]

The subarray() Method

Unlike set(), subarray() doesn't copy anything—it creates a window into the same buffer:

const original = new Uint8Array([10, 20, 30, 40, 50]);
const view = original.subarray(1, 4); // View indices 1-3

console.log(view); // [20, 30, 40]

view[0] = 99; // Modifying the view...
console.log(original); // [10, 99, 30, 40, 50] ...changes the original!

The analogy: subarray() is like looking through a window at part of a room—you're seeing the real thing, not a photograph.

When to Use Each

Use set() when you need to copy data into a specific position. Use subarray() when you want to work with a portion of existing data without the memory overhead of copying.

Key Takeaway: set() copies elements into a typed array at a specified offset, while subarray() creates a view into the same buffer without copying—changing the view changes the original data.