Skip to the content

Printing objects

JavaScript · Unit 12: Classes and objects

If you put an object into a string, with + or in a template, JavaScript has to turn it into text. If you don't tell it how, it writes [object Object], which says nothing.

class Book {
  constructor(title) {
    this.title = title;
  }
}
const b = new Book("Coco");
console.log(`Reading: ${b}`);

Prints

Reading: [object Object]

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Predict the output

    What does this code print?

  3. 3. Complete the code

    Fill in the blank so the template shows "Cat: Kira".

  4. 4. Find the bug

    This program should print "Ticket to Denver" on a single line. Which line has the bug?

  5. 5. Multiple choice

    The class has toString(). What does the last line show?

  6. 6. Predict the output

    What does this code print?

  7. 7. Predict the output

    A hand of cards. What does it print?

  8. 8. Put the lines in order

    Put the program in order: the price is stored in cents and toString() shows it in dollars, like "$3.50". The constructor fits on one line.

  9. 9. Multiple choice

    Emma can't decide between giving her class a toString() that returns the text, or a show() method that prints it. Why is toString() the better choice?

  10. 10. Predict the output

    This is how the receipt comes out. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →