Reading Properties
An object is only useful if you can get its values back. To read a property, write the object's name, a dot and the key:
const book = {
title: "The Hobbit",
author: "J. R. R. Tolkien",
pages: 310
};
console.log(book.title);
console.log(book.pages);The Hobbit
310You already know the dot from arrays: list.length reads the property length of an array.
book.title is a value like any other. You can store it in a variable, calculate with it or put it in a template literal:
const book = { title: "The Hobbit", author: "J. R. R. Tolkien", pages: 310 };
const days = book.pages / 10;
console.log(`${book.title} by ${book.author}`);
console.log("At 10 pages a day, you'll read it in", days, "days.");The Hobbit by J. R. R. Tolkien
At 10 pages a day, you'll read it in 31 days.What if you read a property the object doesn't have? Unlike a misspelled variable name, it isn't an error. You get undefined, the special value you know from arrays, which means “nothing is here”:
const book = { title: "The Hobbit", author: "J. R. R. Tolkien", pages: 310 };
console.log(book.year);
console.log(book.Title);undefined
undefinedThe book has no year. And Title is not title: as with variable names, uppercase and lowercase letters in keys matter. So when you see an undefined you didn't expect, check how you spelled the key.
One more mistake: the key after the dot has no quotes. book."title" ends with SyntaxError: Unexpected string.
Instructions
- 1
The program prints
undefined. Fix the key inconsole.logso that it prints the book's title,The Hobbit. - 2
Below, print the sentence
The Hobbit has 310 pages.Don't type the title and the number yourself: read them from the object withbook.titleandbook.pages, for example in a template literal.