get and set
JavaScript · Unit 14: Modern classes
- Full plan
- JavaScript
- 10 exercises
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. Complete the code
Fill in the blank so
diameterbecomes a computed property of the circle.2. Predict the output
The rectangle changes after it's created. What does it print?
3. Predict the output
What does this code print?
4. Find the bug
This program should print 72, what 3 juices at 24 cost. Which line has the error?
5. Predict the output
The battery can't go above 100. What does it print?
6. Complete the code
The top grade is 10. Fill in the blank so
s.grade = 12leaves 10 in the points.7. Put the lines in order
Put the
Courtclass in order: it stores its side and works out its area with aget.8. Predict the output
The room has 40 seats. What does it print?
9. Multiple choice
An
Orderclass storescostandunits. Why is aget totalbetter than storingthis.totalin the constructor?10. Find the case that fails
average(grades)builds aGroupwith those grades and returns its average, or 0 if the group has none. Which call does it fail on?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.