Advertisement
Intermediate JavaScript, ArrayBuffer, TypedArrays & Binary Data

What's the difference between slice() and subarray() on a TypedArray?

Short answer

slice() copies the selected elements into a brand-new TypedArray backed by a new buffer. subarray() creates a new TypedArray view over the SAME underlying ArrayBuffer — modifying one affects the other.

Save JavaScript mock interview
Advertisement
AModel answer
slice() copies the selected elements into a brand-new TypedArray backed by a new buffer. subarray() creates a new TypedArray view over the SAME underlying ArrayBuffer — modifying one affects the other.
const a = new Uint8Array([1,2,3,4]);
const copy = a.slice(0,2);    // new buffer
const view = a.subarray(0,2); // shares buffer
view[0] = 99;
console.log(a[0]);    // 99
console.log(copy[0]); // 1
Real-world example
subarray() is used to process large binary buffers in chunks without expensive copies.
Likely follow-ups
  • Does this mean subarray() is faster than slice()?
Related topics