Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.4 — map and filter
JavaScript · Example 3 of 3

The classic map and filter traps

map(parseInt) passes the index as parseInt's second argument (the radix). Braces without return give undefined. filter(Boolean) drops every falsy value. map skips holes and keeps them.

map makes a new array by changing every item with a function you give it, and filter makes a new array keeping only the items your function says yes to; neither changes the original, and they chain together into clear data pipelines.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Given const names = ["asha", "ravi"];, make ["Asha", "Ravi"] with map.

02

Given an array of { title, done } tasks, print the titles of the tasks that are not done.

03

Make an array of the even numbers from [1, 2, 3, 4, 5, 6], each squared.

Explain it without notes

01

What is the difference between map and filter?

02

Why does ["1", "2", "3"].map(parseInt) return [1, NaN, NaN]?

03

Why should you filter before mapping when you can?

04

When should you not use map?

The classic map and filter traps

Console

(nothing was printed)

Expected console output

[ 1, NaN, NaN ]
[ 1, 2, 3 ]
[ undefined, undefined, undefined ]
[ { value: 1 }, { value: 2 }, { value: 3 } ]
[ 'hi', 5 ]
[ 10, <empty>, 30 ]