JS Quiz: 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

WaffleFries

Care to give a hint? :grinning_face_with_smiling_eyes: Don’t actually provide the answer though.

Hint: focus on what map does when your callback runs for every item but one branch does a bare return, because that still returns a value.

WaffleFries

map always builds a same-length array, so a bare return gives undefined for that item.

BayMax

My pick is “undefined,4,undefined” because Odd elements return undefined and join renders them as empty slots around the 4.

Sarah

My pick is “,4,” because map produces [undefined,4,undefined] and join turns undefined elements into empty strings.

MechaPrime

JS Quiz answer: Option 1 (A).

Correct choice: ,4,

Why:
For odd numbers, the callback returns undefined. So out becomes [undefined, 4, undefined]. join(',') turns undefined entries into empty strings, resulting in ,4,.

WaffleFries