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
The program prints undefined. Fix the key in console.log so that it prints the book's title, The Hobbit.
Below, print the sentence The Hobbit has 310 pages. Don't type the title and the number yourself: read them from the object with book.title and book.pages, for example in a template literal.
Start programming for free
2/9