Home > Back-end >  How to insert only one return code in JavaScript function with if statement?
How to insert only one return code in JavaScript function with if statement?

Time:06-14

I am trying to learn JavaScript and I wrote a function, that works as an easy calculator. It works OK, but I think there must be a way how to write only one return line of code. Any ideas how to simplify my code? (Without actually rewriting it all :) Thank you for you help! Here is my code:

enter image description here

CodePudding user response:

There is no point in using return in the first place, i would use switch case instead of all these messy if else statements.

switch (operator) {
   case ' ':
      alert(`Your result is ${number1   number2}`);
      break;
   case '-':
      alert(`Your result is ${number1 - number2}`);
      break;
   // and so on
}

CodePudding user response:

let result = 0

if (operator === ' ') result = number1   number2
else if (operator === '-') result = number1 - number 2

alert(result)

Or use a switch

result = 0

switch (operator):
    case ' ':
        result = number1   number2
        break
    case '-':
        result = number1 - number2

alert(result)

If your function doesn't need to return any value just just alert without return.

  • Related