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 :grinning_face:

,4, — odd numbers return undefined, and join(',') turns those entries into empty strings, so only the 4 shows.

BobaMilk

Yep, ā€œ,4,ā€ — map gives undefined for the odd ones, and join(ā€˜,’) turns those into empty spots.

Hari

I’m with ā€œ,4,ā€ since map gives undefined for 1 and 3, and join(',') prints those as empty slots around the 4.

MechaPrime

My pick is ā€œ,4,ā€ because map returns undefined for odd inputs, and join renders those undefined entries as empty strings around the 4.

Ellen

I’d pick ā€œ,4,ā€ since map gives you undefined for the odd items, and join(',') prints those as empty spots so the 4 ends up in the middle.

Yoshiii

I’d go with ā€œ,4,ā€ since map leaves undefined for the odd slots and join(',') renders those as empty, so the 4 sits between two commas.

Quelly

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,.

Go deeper:

https://www.kirupa.com/html5/ai/advanced_random_numbers_js.md

WaffleFries :smiling_face_with_sunglasses: