Skip to content
Advertisement

trying to use switch with if else statement to make operations. but but syntax error appears?

i am a javascript beginner , tried to make a program to insert two inputs of numbers and insert an operator to make a mathematical function and make an alert if the input is not correct. i don’t know why a syntax error appears after case + and doesn’t work .is there other way to make the program? any suggetions? thanks in advance

enter image description here

Advertisement

Answer

There are a few different issues with your code and I’ll go over them one by one:

  • First, note that typeof for first_number and second_number will be number regardless of the input. You want to check for NaN instead using the isNaN function.
  • Second, you will want to wrap the cases of the switch statement in curly braces.
  • Third, the case values themselves should be in quotes in this case.
  • Fourth, you will want the break keyword after each of your cases to prevent them from falling through to the next case. There are valid use cases for that (such as multiple cases with the same block) but it’s not what you want in this basic example.

All in all, your code should look like this, basically:

var first_number = parseInt(prompt("Please enter a number"));
var second_number = parseInt(prompt("Please enter a number"));

if (isNaN(first_number) || isNaN(second_number))
{
    alert("Please enter valid numbers.");
}

var operator = prompt("Please enter an operator");

var result;

switch(operator)
{
    case "+":
        result = first_number + second_number;
        break;

    case "-":
        result = first_number - second_number;
        break;

    case "*":
        result = first_number * second_number;
        break;

    case "/":
        result = first_number / second_number;
        break;

    default:
        result = "Invalid operator.";
        break;
}

alert(result);

Lastly, please post your actual code in the contents of the post in future instead of an image.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement