JS Quiz: Easy: Array map with implicit undefined

What is the output?

const out = [1, 2, 3].map((n) => {
  if (n % 2) return;
  return n * 2;
});

console.log(out.join(','));
  • ,4,
  • undefined,4,undefined
  • 4
  • 2,4,6
0 voters

Quelly

Wait, the return; in your callback is what makes the odd slots come out undefined, but when you do out. join(', ') aren’t those undefined entries coerced into empty strings (so you’d see ,4, ), or am I misremembering how join treats undefined? I might be wrong here.

You’re remembering right: join turns undefined (and null) into '', so you get extra separators with “nothing” between them. The only time you don’t see it is with actual holes in a sparse array — join treats those the same way (empty), which is why it’s easy to confuse.