JavaScript flat(0) Removes Array Holes and Shifts Indexes
Contents
Calling flat(0) on a sparse array can move an item to an earlier index. Depth zero keeps nested arrays intact, but the outer array still gets compacted. If an index identifies a column or a position in a batch, that shift can associate a value with the wrong position.
Check the indexes before and after copying
The first slot in this example is a hole. Index 2 holds an explicit undefined. Run the example in Node.js to see how each operation treats them.
import assert from 'node:assert/strict';
const source = [, 'paid', undefined, [, 'sent']];const spread = [...source];const compact = source.flat(0);const flattened = source.flat(1);const preserved = source.slice();
for (const [name, array] of Object.entries({ source, spread, compact, flattened, preserved,})) { console.log(name, array.length, Object.keys(array).join(','), array.indexOf('paid'));}
assert.equal(Object.hasOwn(spread, 0), true);assert.equal(spread[0], undefined);assert.equal(Object.hasOwn(preserved, 0), false);assert.equal(Object.hasOwn(compact, 1), true);assert.equal(compact[1], undefined);assert.equal(compact[2], source[3]);assert.equal(Object.hasOwn(compact[2], 0), false);assert.deepEqual(flattened, ['paid', undefined, 'sent']);Output on Node.js 24.13.0:
source 4 1,2,3 1spread 4 0,1,2,3 1compact 3 0,1,2 0flattened 3 0,1,2 0preserved 4 1,2,3 1The columns after the name show the length, the own indexes, and the index of 'paid'. Spread keeps the numeric positions and fills the outer hole with undefined. The flat(0) copy moves 'paid' from index 1 to index 0, keeps the explicit undefined, and reuses the nested array. The flat(1) copy also processes that nested array, skipping its hole and appending 'sent'.
Pick the copy based on what the index means
Use slice() to copy an ordinary sparse array when both its index positions and its holes matter. Use spread when positions matter and the consumer expects an own element at every index. Use flat(0) when the result should contain only the occupied outer slots in order and their original indexes can be discarded. These are shallow copies where nested arrays remain as elements.
The ECMAScript flattening algorithm checks whether an index exists before deciding whether to recurse. That check still runs at depth zero. It includes inherited indexed properties, so the example assumes ordinary arrays without inherited numeric entries. If your code reads slots as values, check property presence separately to distinguish a hole from an explicit undefined.
References: