Quiz
Warm-up from lesson 6-2: what does the arrow function n => n * 2 return when called with 5?
Loops you do not have to write
In lesson 4-3 you wrote loops to transform and select. Arrays carry built-in methods that do those jobs in one line. Each takes a function (usually an arrow) and applies it to every item.
map transforms each item and returns a new array of the same length:
const nums = [1, 2, 3, 4, 5]; const doubled = nums.map(n => n * 2); // [2, 4, 6, 8, 10]
filter keeps the items where your arrow answers true, returning a new, possibly shorter array:
const evens = nums.filter(n => n % 2 === 0); // [2, 4]
Neither method touches the original array. And because each returns an array, you can chain them:
prices.filter(p => p >= 10).map(p => p / 2)
Python's list comprehensions covered both jobs: [n * 2 for n in nums] is a map, and [n for n in nums if ...] is a filter.
Code exercise · javascript
Run it. map keeps the length, filter shrinks it, and the chained line does both in one pass of reading.
Code exercise · javascript
Your turn. In lesson 6-1 you wrote the formula c × 9/5 + 32. Use map with an arrow to convert every Celsius temperature to Fahrenheit and print the new array.
Code exercise · javascript
Second practice. From the students array, build an array holding just the NAMES of students who scored 70 or higher: chain filter (keep the passing objects) then map (pull out each name). Print the result.
Quiz
nums has 6 items. nums.map(n => n > 3) returns an array of what length?