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.
Given const names = ["asha", "ravi"];, make ["Asha", "Ravi"] with map.
Given an array of { title, done } tasks, print the titles of the tasks that are not done.
Make an array of the even numbers from [1, 2, 3, 4, 5, 6], each squared.
Explain it without notes
What is the difference between map and filter?
Why does ["1", "2", "3"].map(parseInt) return [1, NaN, NaN]?
Why should you filter before mapping when you can?
When should you not use map?
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 ]