Methods and Parameters Lesson

Method

A method is an action stored inside an object or class. It is written like a function, but it belongs to the object that uses it.

Parameter

A parameter is the placeholder name inside the method definition. It tells the method what kind of input it expects to receive.

Argument

An argument is the real value sent into the method when the method is called. The argument fills the parameter for that run.

A method becomes useful when it can do the same kind of job with different values. In the scoreboard example, the action is adding points. The method does not need to know ahead of time whether the player earned 10 points, 25 points, or some other amount. The parameter gives the method a flexible opening for that value.

Code Runner Challenge

Methods and Parameters Lesson

View IPYNB Source
%%js

// CODE_RUNNER: Methods and Parameters Lesson

class Scoreboard {
  constructor() {
    this.score = 0;
  }

  addPoints(points) {
    this.score = this.score + points;
    console.log("Score: " + this.score);
  }
}

const board = new Scoreboard();
board.addPoints(10);
board.addPoints(25);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...
The method is addPoints. The parameter is points. The arguments are 10 and 25, because those are the real values passed into the method calls. This lets one method update the score in multiple situations without copying the same code.