Somebody please tell me "it's not you, it's javascript"

Here is a simple calculator from an exercise that uses the switch structure:

let num1 = prompt("Enter a number:",0);
let num2 = prompt("Enter another number:",0);
let operator = prompt("Enter an operation +, -, *, /");

if ((Number.isNaN(num1)) || (Number.isNaN(num2))) {
    alert("Invalid entry, enter numbers.")
} else {

switch(operator) {
  case "+":
    alert(num1 + num2);
    break;
  case "-":
    alert(num1 - num2);
    break;
  case "*":
    alert(num1 * num2);
    break;
  case "/":
    alert(num1 / num2);
    break;
  default:
    alert("Enter a valid operator");
    }
}

Why is it that I need to use quotes in each one of the cases in switch?
Why can’t it be?

let num1 = prompt("Enter a number:",0);
let num2 = prompt("Enter another number:",0);
let operator = prompt("Enter an operation +, -, *, /");


if ((Number.isNaN(num1)) || (Number.isNaN(num2))) {
    alert("Invalid entry, enter numbers.")
} else {

switch(operator) {
  case +:
    alert(num1 + num2);
    break;
  case -:
    alert(num1 - num2);
    break;
  case *:
    alert(num1 * num2);
    break;
  case /:
    alert(num1 / num2);
    break;
  default:
    alert("Enter a valid operator");
    }
}

Because those need to be expressions that can be evaluated. A string can be evaluated as an expression. So can a number. But those characters are operators, so they can’t be evaluated as expressions.

If you look at the dev tool’s console you’ll see that you are getting a syntax error on your first case because you have an operator in there instead of an expression.

1 Like

What is the type of data that gets put into operator? It is a string!. The switch needs to match against the exact same type of data.

2 Likes

That would make them identifiers, like variables, functions, or here the actual operators.

console.log(+ == '+'); // SyntaxError: Unexpected token

Also, keep in mind that the switch will do a strict comparison so the types have to match.

const switchOn = '1';

switch (switchOn) {
  case 1:
    console.log('case is never true');
    break;
  case '1':
    console.log('case is "1"'); // case is "1"
    break;
}
1 Like

You are the BOSS. Thanks bro!

Thanks! Some times I miss reading the #$%$#$ing manual.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.