Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

JavaScript · Function

flat

Array.prototype.flat() creates a new array by recursively concatenating nested arrays up to a chosen depth. Without an argument, it flattens one level.

Since
ES2019

How it works

Calling flat() creates a new array by concatenating nested array elements up to the requested depth. The default depth is 1; non-array elements are copied directly, and the original array is not changed.

Syntax

flat()
flat(depth)

Parameters

NameTypeDescription
depthnumber (optional)The depth level specifying how deeply nested arrays should be flattened. Defaults to 1.

Returns

A new array with sub-array elements concatenated into it.

Key points

  • flat() returns a new array containing nested elements concatenated through the specified depth.
  • The depth controls how many nested array levels are recursively flattened.
  • Omitting the depth argument flattens one level.
  • The return value is always a new array.
  • The original array remains unchanged, while object references in the result remain shallowly copied.
  • The method can operate on array-like values with a length and integer-indexed properties.

Common mistakes

  • Sparse arrays lose empty slots at the levels being flattened; deeper nested arrays retain their holes until those levels are flattened.
  • flat() does not mutate the source array; it returns a new shallow-copy array.
  • When called generically on array-like objects, only elements that are arrays are flattened.

Example: Flatten nested arrays

const nested = [1, [2, [3, 4]], 5];

console.log(nested.flat());
console.log(nested.flat(2));

The first call flattens one nesting level; the second flattens two levels.

When to use it

Flatten one level

Turn arrays of arrays into a single-level array.

Flatten multiple levels

Normalize data nested at a known depth.

Use the generic method

Process array-like objects that expose length and integer-indexed properties.

  • Array.prototype.flatMap()
  • Array.prototype.map()
  • Array.prototype.concat()
  • Array.isArray()

Source: Array.prototype.flat() - JavaScript | MDN Web Docs. Checked 2026-10-15.