Skip to the content

Methods

JavaScript · Unit 12: Classes and objects

A method is a function that lives inside the class. You write it without function and call it with a dot and parentheses: r.area().

Inside, this is the object you called it with, so the method can use its data.

class Rect {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
  area() {
    return this.width * this.height;
  }
}
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. Predict the output

    What does this code print?

  2. 2. Complete the code

    Fill in the method that says how many 250 ml cups come out of the thermos.

  3. 3. Predict the output

    Look at the last line. What does it print?

  4. 4. Predict the output

    What does this code print?

  5. 5. Find the bug

    This program should print 2, the lives Noah has left after crashing. Which line has the bug?

  6. 6. Complete the code

    Fill in the blank so the jar has an add method that stores coins.

  7. 7. Find the bug

    This program should print how many liters of paint the wall needs, 3. Which line has the bug?

  8. 8. Put the lines in order

    Put the program in order: use drains the phone's battery and returns how much is left. The constructor fits on one line; it's the same as on several.

  9. 9. Find the case that fails

    count(names) puts each name into a Group and returns how many people ended up in it. The add method shouldn't add the same person twice. Which call fails?

  10. 10. Predict the output

    Liam adds up his grocery bill. 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 →