back to the lesson

Create a calculator

importance: 5

Create an object calculator with three methods:

  • read() prompts for two values and saves them as object properties with names a and b respectively.
  • sum() returns the sum of saved values.
  • mul() multiplies saved values and returns the result.
let calculator = {
  // ... your code ...
};

calculator.read();
alert( calculator.sum() );
alert( calculator.mul() );

Run the demo

Open a sandbox with tests.

let calculator = {
  sum() {
    return this.a + this.b;
  },

  mul() {
    return this.a * this.b;
  },

  read() {
    this.a = +prompt('a?', 0);
    this.b = +prompt('b?', 0);
  }
};

calculator.read();
alert( calculator.sum() );
alert( calculator.mul() );

Open the solution with tests in a sandbox.