whatstheoutput_

#37: Array(3).fill(0) vs Array(3).map(...)

Topic: arrays · Difficulty: ★★

const a = Array(3).fill(0);
const b = Array(3).map(x => 1);
console.log(a);
console.log(b);

Output

[ 0, 0, 0 ]
[ <3 empty items> ]

Why

Array(3) creates an array with length 3 but no actual elements — three 'holes', not three undefineds. fill(0) writes an actual value into every index, producing a normal [0, 0, 0]. But map() only invokes its callback on indices that exist; empty slots are skipped entirely, so mapping over Array(3) never calls the callback and returns another array of three untouched holes, printed as '<3 empty items>'. This is why Array(3).map(...) is a classic trap for 'range' tricks — Array.from({length:3}) or Array(3).fill() must be used instead.

More arrays puzzles

Play today's puzzle →