JavaScript Basics · Lesson 9 of 13

Working With Lists

Looping over an array to build a new one is so common that arrays have methods for it. To use them you need a shorter way to write small functions.

Arrow functions

An arrow function is a compact function without a name:

const double = (n) => n * 2;
console.log(double(5));   // 10

Before the arrow => are the parameters. After it is the value to return. No function, no braces and no return needed for a one-line calculation.

map: change every item

map runs a function on each item and collects the results in a new array of the same length:

const prices = [10, 20, 30];
const withTax = prices.map((p) => p * 1.2);
// [12, 24, 36]

filter: keep some items

filter runs a test on each item and keeps only the ones where the test is true:

const big = prices.filter((p) => p > 15);
// [20, 30]

Neither method changes the original array.

Other useful ones

  • .join(", ") glues all items into one string, with the given text between them.
  • .find((x) => …) returns the first item that passes the test.
  • .sort() puts strings in alphabetical order.
  • .reduce((sum, x) => sum + x, 0) boils an array down to one value, here the total.

These methods can be chained: the result of one becomes the input of the next.

const names = ["li", "omar", "eve"];
console.log(names.map((n) => n.toUpperCase()).join(" & "));   // LI & OMAR & EVE

Your Task

  1. Use filter to create adults: only the ages that are 18 or more.
  2. Use map to create nextYear: every age from ages, plus 1.
  3. Print adults, then print nextYear.
  • adults holds only the ages of 18 and over
  • It is made with filter
  • nextYear holds every age plus 1
  • It is made with map, and ages itself is unchanged
  • Both arrays are printed