Summary

In this lesson, you learned that:

  • Arrays have methods that replace the most common loops. Most of them take a callback: a function, usually an arrow function, that the method calls for each element, such as (animal) => animal.age < 5.
  • filter() returns a new array with the elements for which the callback returns true. Its length tells you how many there are.
  • map() returns a new array with whatever the callback returns for each element: animals.map((animal) => animal.name).
  • forEach() just calls the callback for each element, like a for...of loop.
  • find() returns the first element for which the callback returns true, or undefined if there's none. some() tells you whether at least one element meets the condition, every() whether all of them do.
  • join(", ") joins the elements into one text, with ", " between them.
  • Methods can be chained: animals.filter(...).map(...).join(", "). First pick the elements, then convert them.
  • sort() sorts the array itself. Without a compare function, it compares the elements as texts, so [10, 9, 1] becomes [1, 10, 9]. Numbers are sorted with (a, b) => a - b, or b - a for the largest first, and texts with (a, b) => a.localeCompare(b).
  • Spread, the three dots, copies: [...temperatures] is a new array, [...morning, ...afternoon] joins two arrays, and { ...leo, age: 7 } is a changed copy of an object. When you need the original order too, sort a copy.
  • Destructuring takes values out of an object by their names, const { name, age } = leo;, and out of an array by their positions, const [first, second] = ages;.

Next comes one more small project, a football league table, in which you'll put functions, objects and these methods to work. Then, in the lesson JavaScript on Web Pages, your code will run on a web page: it will change what the page shows and react to clicks. And you'll see that the parts of a web page are objects too, with properties you can read and change.

Now some practice. The zoo in the editor keeps a list of its animals.

Instructions

Print the names of the animals that are at least 5 years old, in alphabetical order and separated by commas: Older animals: Bruno, Coco, Ella, Leo.

Below, print the youngest animal: Youngest: Pip (penguin). Sort a copy of animals by age, and take the first animal out of it with destructuring.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

10/10

Next