Technical skill practice

JavaScript Array map: Transform Records and Return Each Result

map creates an array from the callback result at each visited position. Use it for transformation rather than selection or side-effect-only work. An omitted return can produce undefined entries instead of the expected values.

The task

Build display records from a small delivery list and keep the nested location reference visible. Compare a correct returned object with a callback that forgets to return.

Runnable Node 22 example

const assert = require('node:assert/strict');

const deliveries = [{id: 'D1', location: {room: '4'}}, {id: 'D2', location: {room: '8'}}];
const labels = deliveries.map(item => ({label: `Delivery ${item.id}`, location: item.location}));
assert.equal(labels.length, deliveries.length);
assert.equal(labels[0].label, 'Delivery D1');
assert.equal(labels[0].location, deliveries[0].location);
const missing = deliveries.map(item => { item.id; });
assert.deepEqual(missing, [undefined, undefined]);
assert.equal(deliveries[0].label, undefined);
console.log(labels.map(item => item.label).join(' | '));

Expected output and explanation

The callback returns a new outer display record for each input, so the result keeps the two-item length. The original records do not gain a label property. The location field remains shared because the callback deliberately reuses that nested reference.

The block-bodied callback in missing evaluates an expression but returns nothing, producing two undefined values. Parenthesized object expressions or an explicit return can avoid that mistake. The choice should be visible in code rather than repaired by filtering away the missing results afterward.

Output from the example

Delivery D1 | Delivery D2

Pitfall to check

map does not filter out entries when a callback returns undefined, and it is not a deep-copy promise. Use filter for a membership condition and a separate copy strategy when nested independence is required.

Questions, answered

Should I use map just to print each input?

forEach or a loop better expresses side effects when no transformed result is needed. map is useful when its returned array is the intended output.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.