JavaScript traps · JavaScript

JavaScript: [,,,].length = 3?!PRO

Each comma ends a slot and the last (trailing) comma is ignored: three commas make three empty slots.

// [,,,].length = 3 ?!
// Each comma ends a slot, and the LAST comma is ignored (a trailing comma).
console.log([,,,].length);          // 3 ?!  three commas, three EMPTY slots
console.log([1, 2, 3,].length);     // 3     the last comma never counts

// Empty slots are holes, not undefined: map and forEach skip them
console.log([,,,].map(x => 1).length);   // 3, but no 1s inside
// Fix: fill the holes before you use them
console.log(Array(3).fill(1).join(" "));  // 1 1 1 ✓
Open code JS13 in Pocket Compiler Download the Pocket Compiler app — free

No app yet? Install it, then open the app and type the code JS13 in Code Library.