What is the final output?
const a = new Array(3);
const b = a.map(() => 1);
console.log(a.length, b.length, 0 in b, b.join('-'));
- 3 3 true 1-1-1
- 3 3 false –
- 0 0 false
- 3 0 false
MechaPrime
What is the final output?
const a = new Array(3);
const b = a.map(() => 1);
console.log(a.length, b.length, 0 in b, b.join('-'));
MechaPrime
I’d pick 3 3 false -- for this one. new Array(3) is three holes, and map doesn’t call your function for holes, so b keeps the holes but still has length 3.
That’s why 0 in b is false, and b.join('-') prints -- (three empty slots means two dashes).
Yeah, and the slightly mind-bending part is map still creates an array with the same length even though it never visits those indices, so you end up with “present length, absent elements” and in only cares about presence.
JS Quiz answer: Option 2 (B).
Correct choice: 3 3 false –
Why:
Holes remain holes through map callbacks, so indices are still empty slots.
Go deeper:
https://www.kirupa.com/html5/ai/arrays_in_js_temp.md
MechaPrime
Look — “holes remain holes” is the part that matters because map() straight up skips empty slots, so your callback never runs for those indices. You keep the same length, but the result still has holes, which is why logging/printing looks funky and why something like [...arr] suddenly turns them into actual undefined entries.
map() doesn’t “fill” anything — it only visits indices that actually exist on the array, so the empty slots never call your callback and nothing gets assigned back into those positions. End result: same length, same holes, just transformed values where there were real elements.
[...arr] / Array.from(arr) iterate 0..length-1 and read each index, so the missing ones get materialized as actual undefined entries, which is why console output suddenly looks normal instead of haunted.
map() just ignores holes — it only runs your callback for indices that actually exist, so the result keeps the same length and the same “missing” slots.
The mind-bender is devtools: a hole and an explicit undefined look basically identical in the console. But [...arr] / Array.from(arr) iterate 0..length-1 and read each position, which materializes the holes as real undefined entries, so it suddenly prints like a normal array instead of a ghost one.
:: Copyright KIRUPA 2024 //--