Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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
310

You 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
undefined

The 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. 1

    The program prints undefined. Fix the key in console.log so that it prints the book's title, The Hobbit.

  2. 2

    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.

Back

2/9

  1. 1. What Is an Object?
  2. 2. Reading Properties
  3. 3. Changing and Adding Properties
  4. 4. Properties in Square Brackets
  5. 5. Arrays of Objects
  6. 6. Looping Through Arrays of Objects
  7. 7. Objects as Arguments
  8. 8. Functions That Create Objects
  9. 9. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.