Nikita Kornienko
Nikita Kornienko

Reputation: 67

How to fix a simple js calculator (returns undefined)

I have this task to create a calculator using only one JS object. No matter what I do it returns 'undefined' and I can't understand what is wrong. I understand that it has something to do with default values, but not stating 'undefined' deliberately has also return an error. All the methods should work fine, but somehow they just don't.

var Calculator = {
  x: undefined,
  y: undefined,
  addition: function() {
    var result = this.x + this.y;
    return result;
  },
  division: function() {
    var result = this.x / this.y;
    return result;
  },
  multiplication: function() {
    var result = this.x * this.y;
    return result;
  },
  subtraction: function() {
    var result = this.x - this.y;
    return result;
  },
  calulation: function() {
    var mathSign;
    this.x = +prompt('Please insert a first number: ');
    this.y = +prompt('Please enter a second number: ');
    if (isNaN(this.x) || isNaN(this.y)) {
      alert('Please insert a number!');
      this.x = +prompt('Please insert a first number: ');
      this.y = +prompt('Please enter a second number: ');
    }
    mathSign = prompt('Please enter a math symbol: (+, -, *, /)');
    if (mathSign == '+' || mathSign == '-' || mathSign == '*' || mathSign == '/') {
      switch (mathSign) {
        case '+':
          this.addition();
        case '-':
          this.subtraction();
        case '*':
          this.multiplication();
        case '/':
          this.division();
      }
    } else {
      alert('An input should be a math symbol! (+, -, *, /)')
    }
  }
}

console.log(Calculator.calulation());

Upvotes: 1

Views: 409

Answers (1)

BenM
BenM

Reputation: 53198

You never return any value from the calculation() function. You need to return the value of the function result inside your switch():

switch(mathSign) {
    case '+': 
        return this.addition();
    case '-':
        return this.subtraction();
    case '*': 
        return this.multiplication();
    case '/':
        return this.division();
}

Upvotes: 5

Related Questions