Brad
Brad

Reputation: 55

Why switch doesn't work while if statement does work

I need some help about what's wrong with switch in the following easy script.

var pp = 1;
switch (pp) {
    case pp == 1:
        var p = "A";
        break;
    default:
        var p = "F";
        break;
}

document.write(p); //display "F" ---??? it should be "A".

if (pp == 1) document.write("A"); //display "A"

Upvotes: 2

Views: 79

Answers (4)

Yosvel Quintero
Yosvel Quintero

Reputation: 19060

If you definitely need you make a reevaluation for every cases you can pass true as expression to the switch statement:

var p,
    pp = 1;

switch (true) {
    case pp === 1:
        p = 'A';
        break;
    default:
        p = 'F';
}

console.log(p); // p should be "A"

if (pp === 1) {
    console.log('A'); // display "A"
}

Upvotes: 0

DnwAlgorithma
DnwAlgorithma

Reputation: 119

Javascript Switch-cause should follow this format

switch(expression) {
case n:
    code block
    break;
case n:
    code block
    break;
default:
    default code block
}

so,case pp==1 is in wrong format.it should be correct as follows

<script>
          var pp=1;
          switch(pp){
              case 1  : var p="A"; break;
              default : var p="F"; break;
          }
          document.write(p);

          if (pp==1) document.write("A");

   </script>

Upvotes: 0

Qiniso
Qiniso

Reputation: 2629

You are re-evaluating the value of pp.

Should be

case 1:
....
break;

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67187

You are using the switch - case syntax in a wrong way,

  switch(pp){
      case 1  : var p="A"; break;
      default : var p="F"; break;
  }

You could also write your code like below,

var p = pp ? "A" : "F"; //And this code is valid for your given data only.

Upvotes: 4

Related Questions