In JavaScript, how does a typed array such as Uint8Array differ from a regular Array in length, holes, element values and available methods?
answer
- a window, not a list
- no push, no splice, no concat
- conversion happens on every write
- map keeps the element type
- subarray shares, slice copies
basics
~20 sA typed array has no push or splice and no holes; every in-range index holds a value of one numeric type, zero by default. Out-of-range writes do nothing, map keeps the type, subarray shares memory and slice copies.
solid answer
~40 sA typed array is a view over a buffer, so it behaves like a window rather than a growable list. `push`, `pop`, `shift`, `unshift`, `splice`, `concat` and `flat` do not exist, and its length changes only when the buffer underneath is resized or detached. Every index in range holds a value of one numeric type, zero by default, so there are no holes, and assigning converts the value to that type. Writing out of range does nothing and does not throw, even in strict mode. `map` and `filter` return the same typed array type, so `new Uint8Array([200]).map(x => x * 2)` holds `144`, not `400`. `sort()` is numeric by default. `subarray` returns a view of the same memory, while `slice` copies. `Array.isArray` returns `false`, and `JSON.stringify` produces an object with numeric keys.
code
javascript · 8 linesconst u8 = new Uint8Array(3);
console.log(1 in u8); // true
u8[5] = 1;
console.log(u8[5], u8.length); // undefined 3
console.log(typeof u8.push); // undefined
console.log(Array.isArray(u8)); // false
console.log(new Uint8Array([200]).map((x) => x * 2)[0]); // 144
console.log(new Uint8Array([10, 9, 1]).sort().join()); // 1,9,10go deeper
Recall the visible differences: one numeric type, no push or pop, and zeros in place of holes. Know that Array.isArray returns false for a typed array.
Explain the less visible behaviour: silent out-of-range writes, conversion on every write, map staying in the element type, numeric default sort, and subarray sharing memory where slice copies.
Show how these bite in production: a map whose results wrap, a subarray returned from a helper that later sees overwrites, and JSON output shaped as an object. Say how you would guard each one.
Weigh where typed arrays belong at all. Their memory layout pays off for large numeric data and binary interfaces, while a regular Array stays simpler for small lists, so state where a team should draw that line.
## Why the differences exist A regular `Array` is a general list of values: it can grow, it can hold strings next to objects, and it can have missing indexes. A **typed array** is a fixed-format view over bytes in an `ArrayBuffer`, where every index maps to a computed position in that memory. Almost every difference below follows from this. There is nowhere to put a new element, no way to store a string in four bytes meant for an integer, and no such thing as a missing byte. | Behaviour | `Array` | Typed array | |---|---|---| | Change the length | `push`, `splice`, `length = n` | only through the buffer underneath | | Holes | possible | none | | Element values | anything | one numeric type, converted on write | | Write past the end | grows the array | ignored, no error | | `map`, `filter` result | `Array` | same typed array type | | `sort()` default | as strings | numeric | | `Array.isArray` | `true` | `false` | | `JSON.stringify` of `[1, 2]` | `[1,2]` | `{"0":1,"1":2}` | ## Length and the missing methods The method lists overlap but do not match: - **Missing because they would change the length:** `push`, `pop`, `shift`, `unshift` and `splice`. - **Also missing:** `toSpliced`, `concat`, `flat` and `flatMap`. - **Shared with `Array`:** most of the rest, including `forEach`, `reduce`, `find`, `includes`, `join`, `toSorted` and `with`. - **Only on typed arrays:** `set` and `subarray`. The length is not strictly constant, and it pays to know the exceptions: - A view with no explicit length over a **resizable** `ArrayBuffer` tracks that buffer as it changes size. - A view whose buffer has been **detached** reports a length of 0. Assigning to `length` never changes it: the property has only a getter, so the assignment is ignored in sloppy mode and throws `TypeError` in strict mode. To append to a typed array, you build a new one: 1. Allocate a new typed array of the combined length. 2. Call `out.set(first)` to copy the first run. 3. Call `out.set(second, first.length)` to copy the next run after it. `set` throws `RangeError` if the source would not fit at that offset. ## Holes and element values `new Uint8Array(3)` holds three zeros, and `1 in u8` is `true`, because every index below `length` exists. There is no sparse form. Numeric indexes are handled by the view itself and never reach the prototype chain, so out-of-range reads return `undefined` and out-of-range writes change nothing. That silence is a trap: `u8[5] = 1` on a three-element array raises no error even in strict mode, and code that relied on the array growing just loses data. Each write converts the value to the element type. A `Uint8Array` keeps the low 8 bits of the truncated number, so large results wrap instead of being stored. ## Results that keep the element type This is the difference that causes real bugs. `map` and `filter` return a new typed array of the same type, so the results of `map` go through that conversion: ```js const u8 = new Uint8Array([200]); console.log(u8.map((x) => x * 2)[0]); // 144 console.log(Array.from(u8, (x) => x * 2)[0]); // 400 ``` `400` does not fit in a byte and wraps to `144`. When a transformation can leave the element's range, use `Array.from` with a mapping function, which produces a plain `Array`, or map into a wider typed array. ## subarray shares, slice copies ```js const a = new Uint8Array([1, 2, 3, 4]); const shared = a.subarray(1, 3); const copied = a.slice(1, 3); a[1] = 99; console.log(shared[0]); // 99 console.log(copied[0]); // 2 ``` `subarray` creates a new view over the same `ArrayBuffer`, with its `byteOffset` moved along. `slice` copies the range into a new buffer. Regular arrays have no `subarray`, so this aliasing is new to anyone coming from `Array.prototype.slice`. ## Getting out to a regular array - `Array.from(typed)` or `[...typed]` gives a plain `Array` when you need `push` or JSON output. - `new Uint8Array(array)` goes the other way, converting each element. - `Object.freeze` on a non-empty typed array throws `TypeError`, since the bytes could still change through another view, so immutability needs a copy and discipline rather than a freeze.
- Why does `Object.freeze` throw on a non-empty typed array?`Object.freeze(new Uint8Array(1))` throws `TypeError` because a frozen object must never change, and a typed array cannot promise that. Its elements live in an `ArrayBuffer`, and any other view of that buffer can rewrite them. An empty typed array has no elements and can be frozen.
- What does `JSON.stringify(new Uint8Array([1, 2]))` return, and how do you get a JSON array?It returns `{"0":1,"1":2}`, because JSON treats a typed array as an object whose keys are its indexes, since it is not a real `Array`. Convert first with `Array.from(typed)` or `[...typed]`, then stringify. Parsing the result gives a regular array, so wrap it in a typed array constructor to get back.
- When would you choose `subarray` over `slice` on a typed array?`subarray` is the cheap one: it only creates a new view, with no bytes copied. `slice` allocates a new buffer and copies the range. The choice is really about ownership, though. Use `subarray` when the caller should see later writes, and `slice` when the result must stay independent.
- Typed arrays have push and pop, just like a regular Array.
- Writing past the end of a typed array grows it, as on a regular Array.
- map on a Uint8Array returns a plain Array, so large results are preserved.
- subarray copies the selected range, exactly as slice does.
- Sorting a typed array without a comparator sorts its numbers as strings.
- A new typed array is full of holes until you assign to each index.