The Array.prototype.flat() Method
What you'll learn: How to use flat() to "unwrap" nested arrays and consolidate their elements into a single, flatter array structure.
Why Flat Exists
Sometimes you end up with arrays inside arrays—maybe from mapping operations or data structures that naturally nest. The flat() method solves the problem of "peeling off" layers of nested arrays to make them easier to work with.
Think of nested arrays like Russian nesting dolls. The flat() method opens them up and lays all the contents out on a table.
Basic Usage
By default, flat() removes one level of nesting:
const nested = [1, 2, [3, 4], 5];
const flattened = nested.flat();
console.log(flattened); // [1, 2, 3, 4, 5]
Notice how the inner [3, 4] array was "unwrapped" but the outer structure remains a single array.
Controlling Depth
The optional depth parameter tells flat() how many levels deep to flatten:
const deepNested = [1, [2, [3, [4]]]];
console.log(deepNested.flat(1)); // [1, 2, [3, [4]]]
console.log(deepNested.flat(2)); // [1, 2, 3, [4]]
console.log(deepNested.flat(Infinity)); // [1, 2, 3, 4] - all levels
Use Infinity as the depth when you want to flatten everything, no matter how deeply nested.
Non-Mutating
Like other modern array methods, flat() returns a new array—it doesn't modify the original:
const original = [1, [2, 3]];
const result = original.flat();
console.log(original); // [1, [2, 3]] - unchanged
Key Takeaway: flat() is a non-mutating method that removes nested array layers, with an optional depth parameter (default 1) to control how many levels to unwrap—use Infinity to flatten completely.