⚡ The Flatten That Only Went One Floor Down
Array.prototype.flat() takes an optional depth argument controlling how many levels of nested arrays it flattens, and it’s easy to assume calling it with no argument at all flattens everything, the way a method simply named ‘flat’ sounds like it should. The actual default depth is 1, not Infinity – a single call only flattens one level of nesting, leaving any array nested two or more levels deep still wrapped in its own array inside the result. Data that happens to be nested exactly one level deep flattens correctly and the code ships looking right, right up until a source that produces two or three levels of nesting runs through the same call and silently leaves nested arrays sitting inside what was supposed to be a flat list.
🔎 The Problem
const groups = [[1, 2], [3, [4, 5]], [6]]; // Looks like it should fully flatten - the method is just called // "flat", after all. The default depth argument is 1, not Infinity. const result = groups.flat(); console.log(result); // [1, 2, 3, [4, 5], 6] // The [4, 5] sub-array is still nested - it was two levels deep, // and only one level of flattening happened. // Code downstream expects a flat array of numbers and silently // gets a mixed array containing a nested array instead - no error, // just wrong data shape further down the pipeline. const total = result.reduce((sum, n) => sum + n, 0); // NaN - adding a number to an array produces NaN, with no // exception pointing back at the actual root cause.
✅ Fix: Be Explicit About the Depth You Actually Need
- Pass Infinity explicitly – array.flat(Infinity) – whenever the intent is to fully flatten arbitrarily nested data, rather than relying on the default, which only handles exactly one level.
- If the maximum nesting depth is known and fixed, pass that exact number instead of guessing, making the intended depth visible in the code rather than implicit in whatever the default happens to be.
- Add a test case using data nested more than one level deep specifically, since data nested exactly one level will pass with the default and never reveal that deeper nesting isn’t handled.
⚠️ Why This Is Easy to Miss
- The method’s name alone – flat() – reads as a complete, no-argument guarantee of a fully flat result, which is a reasonable assumption that happens to be wrong about exactly this one default value.
- Works correctly for any data source that happens to nest exactly one level deep, so the bug only appears once a different or evolving data source starts producing two or more levels of nesting that the original testing never exercised.
flat() with no argument doesn’t mean ‘fully flatten’ – it means ‘flatten exactly one level’, and the method’s own name is the only thing suggesting otherwise.
