Array.prototype.flat
Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth
Syntax
array.flat(depth?)Parameters
| Parameter | Type | Description |
|---|---|---|
| depth | number | Depth level specifying how deep a nested array structure should be flattened. Defaults to 1 |
Return Value
A new array with the sub-array elements concatenated
Examples
const nested = [1, [2, 3], [4, [5, 6]]];
console.log(nested.flat()); // [1, 2, 3, 4, [5, 6]]const deep = [1, [2, [3, [4]]]];
console.log(deep.flat(Infinity)); // [1, 2, 3, 4]const withHoles = [1, , 3, , 5];
console.log(withHoles.flat()); // [1, 3, 5]Understanding Array.prototype.flat
The Array.prototype.flat method in JavaScript creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. It belongs to the Array object and is one of the most widely used methods for working with array values in modern JavaScript and TypeScript applications.
The method signature is array.flat(depth?). It accepts 1 parameter: depth. When called, it returns a new array with the sub-array elements concatenated. Understanding when and how to use flat() helps you write more expressive, readable code.
Common use cases for Array.prototype.flat include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like array-flatmap, array-concat, array-map, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for Array.prototype.flat is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
Array.prototype.flatMapReturns a new array formed by applying a given callback function to each element of the array, then flattening the result by one level
Array.prototype.concatMerges two or more arrays into a new array without changing the existing arrays
Array.prototype.mapCreates a new array populated with the results of calling a provided function on every element in the calling array
More Array Methods
Other methods in the Array object
Related Tools
More Array Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.