Three pieces, with separate jobs:
ArrayBufferowns a contiguous block of bytes, zero-filled, with abyteLength. It has no indexing;slice()copies a range into a new buffer.- Typed arrays (
Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array) are array-like views over a buffer. Each has an element type,BYTES_PER_ELEMENT, abyteOffset, and alength.new Uint8Array(buffer)shares the memory,new Uint8Array([1, 2])ornew Uint8Array(4)allocates a fresh buffer. DataViewis a view with no fixed element type.getUint16(byteOffset, littleEndian),setFloat32(...)and similar read or write at any byte offset, unaligned, with the byte order you pass.
Behaviours interviewers probe:
- Views alias. Writing through one view is visible through all others on the same buffer.
subarray()returns a new view on the same buffer;slice()copies. - Endianness. A typed array stores multi-byte elements in the host's byte order (implementation-defined in the spec; most current hardware is little-endian).
DataViewdefaults to big-endian (network order) unlesslittleEndianistrue. UseDataViewfor file and network formats. - Alignment. A typed array's
byteOffsetmust be a multiple of its element size, and the buffer length must be a multiple of the element size if you don't pass a length, or it throwsRangeError.DataViewhas no such limit. - Element conversion. Writing wraps modulo 2ⁿ for integers (
Uint8Array255 + 1is0), saturates forUint8ClampedArray, and rounds to nearestFloat32for floats. Writes never throw: an index outsidelengthis silently ignored, and reads giveundefined. - BigInt arrays only accept BigInt values.
- Typed arrays aren't
Arrays.Array.isArrayisfalse, they have fixed length, and they lackpushandpop, but they share most iteration methods. Theirsort()is numeric by default, unlikeArray.prototype.sort.