Skip to the content

get and set

JavaScript · Unit 14: Modern classes

A method with get in front of it is used without parentheses, as if it were a property. The difference is that nothing is stored: it's worked out every time you ask for it.

That's why it's called a computed property.

class Rect {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  get area() {
    return this.a * this.b;
  }
}
const r = new Rect(3, 4);
console.log(r.area);

Prints

12

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. Complete the code

    Fill in the blank so diameter becomes a computed property of the circle.

  2. 2. Predict the output

    The rectangle changes after it's created. What does it print?

  3. 3. Predict the output

    What does this code print?

  4. 4. Find the bug

    This program should print 72, what 3 juices at 24 cost. Which line has the error?

  5. 5. Predict the output

    The battery can't go above 100. What does it print?

  6. 6. Complete the code

    The top grade is 10. Fill in the blank so s.grade = 12 leaves 10 in the points.

  7. 7. Put the lines in order

    Put the Court class in order: it stores its side and works out its area with a get.

  8. 8. Predict the output

    The room has 40 seats. What does it print?

  9. 9. Multiple choice

    An Order class stores cost and units. Why is a get total better than storing this.total in the constructor?

  10. 10. Find the case that fails

    average(grades) builds a Group with those grades and returns its average, or 0 if the group has none. Which call does it fail on?

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 →