Summary

In this lesson, you learned that:

  • An object keeps together values that describe one thing: { name: "Rex", species: "dog", age: 3 }. It is made of properties: a key, a colon and a value. Properties are separated by commas.
  • console.log(pet) prints an object the way it's written in code. To add a label, separate it with a comma: console.log("Pet:", pet). With +, the object would turn into [object Object].
  • You read a property with a dot: pet.name. A property the object doesn't have gives undefined. Uppercase and lowercase letters in keys matter.
  • In square brackets, the key can be in a variable: stock[fruit]. stock["peaches"] is the same as stock.peaches.
  • Assigning changes a property (pet.age = 3;) or adds a new one (pet.owner = "Eva";). This works on an object in a constant too; you just can't put a different object in the constant.
  • An array of objects holds many objects of the same kind. pets[1].name is the name of the second pet.
  • A for...of loop goes through such an array one object at a time. You can print the objects, add up a property or pick some of them with if.
  • A function can take an object or an array of objects as an argument, and it can return a new object.
  • A function stored in an object is called a method, like log in console.log().

In the next 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 library in the editor keeps a list of its books.

Instructions

Write a function printAvailable that takes an array of books and prints the title of each book that is available. Call it with books: it should print Matilda and The Hobbit. Tip: available is already true or false, so you can use it as the condition directly: if (book.available).

Someone has just borrowed Matilda. Below the call, set the available property of the first book to false and call printAvailable(books) again. This time it should print only The Hobbit.

Start programming for free

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

Or sign up with:

9/9