CKTIS / JavaScript
Array.prototype.flat: flattening nested arrays
flat returns a new shallow array while spreading nested arrays up to a requested depth.
Version: ECMAScript 2026 draft; example target: Node.js 24.22.2
Syntax
array.flat([depth])array.flat([depth]) creates a new array and spreads elements that are arrays up to depth; the default is 1. The argument is truncated to an integer: a non-positive value produces a shallow copy, while Infinity requests complete flattening. An array-like object that is not an Array is not spread.
The source is not mutated and object references remain shared. Holes at visited levels are skipped, so the result can be denser. The result honors the species constructor; getter and proxy errors propagate. A null or undefined receiver throws TypeError. The example flattens two levels, removes their holes, and preserves source length.
Examples
const source = [1, , [2, , [3]]];
const result = source.flat(2);
console.log(result.join(","), result.length);
console.log(source.length);Result
1,2,3 3 3