Question presented to candidate: "You have an 8-byte ArrayBuffer that a video-processing pipeline needs to hand off to a Web Worker without copying the bytes. Walk me through what buf.transfer() actually does to the original buffer, how it differs from transferToFixedLength(), and what happens if code somewhere still holds a TypedArray view over the original buffer after the transfer."
What a strong answer should cover:
- transfer() moves the underlying memory to a brand-new ArrayBuffer and detaches the original in place — the original's byteLength becomes 0 and its detached property becomes true, with no bytes actually copied.
- A TypedArray view over a detached buffer does not throw on simple reads: .length and .byteLength silently report 0, and an index read returns undefined. Only a WRITE, such as .set(), throws a TypeError.
- transfer(newLength) can also grow (zero-filled) or shrink the buffer as part of the same call — a separate resize() step is not required.
- transferToFixedLength() always produces a non-resizable result, even when the source was a resizable ArrayBuffer created with maxByteLength — this is the one concrete behavioral difference from plain transfer(), which preserves the source's resizable-ness and maxByteLength.
- Calling transfer() a second time on an already-detached buffer throws a TypeError rather than silently no-oping.
- This is the same underlying detach mechanism postMessage/structuredClone have used for years via an explicit transfer list — these methods just expose it as a direct, synchronous API instead of requiring a message-passing round trip.
Clarifying questions expected:
- "Does the receiving side need the resizable-ness of the buffer preserved, or is a fixed-length copy acceptable?" — this determines transfer() vs transferToFixedLength().
- "Is there code elsewhere holding a TypedArray view over the original buffer that needs a defensive check?" — every existing view over the original becomes a permanently zero-length view immediately after transfer.
Code / implementation expected: Yes — real, executed calls to transfer() and transferToFixedLength() on both plain and resizable ArrayBuffers, showing the actual detached state and a real thrown error, not just a description of the spec.