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 givesundefined. Uppercase and lowercase letters in keys matter. - In square brackets, the key can be in a variable:
stock[fruit].stock["peaches"]is the same asstock.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].nameis the name of the second pet. - A
for...ofloop goes through such an array one object at a time. You can print the objects, add up a property or pick some of them withif. - 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
loginconsole.log().
In the next lesson, Array Methods, you'll learn methods that do the work of many loops from this lesson in a single line: they pick objects from an array, convert them into other values, find one of them or sort them. After it comes one more small project, a football league table, in which you'll put functions, objects and array methods to work.
Now some practice. The library in the editor keeps a list of its books.
Instructions
- 1
Write a function
printAvailablethat takes an array of books and prints the title of each book that is available. Call it withbooks: it should printMatildaandThe Hobbit. Tip:availableis alreadytrueorfalse, so you can use it as the condition directly:if (book.available). - 2
Someone has just borrowed Matilda. Below the call, set the
availableproperty of the first book tofalseand callprintAvailable(books)again. This time it should print onlyThe Hobbit.