conditional switch statement javascript code example

Example 1: switch javascript

switch (a) {
    case 1:
        alert('case 1 executed');
        break;
    case 2:
        alert("case 2 executed");
        break;
   case 3:
        alert("case 3 executed");
        break;
    case 4:
        alert("case 4 executed");
        break;
    default:
        alert("default case executed");
}

Example 2: switch statement javascript

function caseInSwitch(val) {
  var answer = "";
  // Only change code below this line
switch(val) {
  case 1:
    answer = "alpha";
    console.log(answer);
    break;
  case 2:
    answer = "beta";
    break;
  case 3:
    answer = "gamma";
    break;
  case 4:
    answer = "delta";
    break;
}


  // Only change code above this line
  return answer;
}

caseInSwitch(1);

Example 3: js convert if/else statement to switch case

var gradeOut = 70;
var totalGrade = 80;

if (gradeOut >= 90)
    gradeOut+= "My letter grade is: A";
  else if (totalGrade < 90 && totalGrade >= 80)
    gradeOut+= "My letter grade is: B";
  else if (totalGrade < 80 && totalGrade >= 70)
    gradeOut+= "My letter grade is: C";
  else if (totalGrade < 70 && totalGrade >= 60)
    gradeOut+= "My letter grade is: D";
  else if (totalGrade < 60)
    gradeOut+= "My letter grade is: F";

//here's the same thing using switch(true). Requires var gradeOut (is currently at top of page
switch(true) {
case gradeOut<60:
    gradeOut= "My letter grade is: F";
    break;
case gradeOut<70:
    gradeOut= "My letter grade is: D";
    break;
case gradeOut<80:
    gradeOut="My letter grade is: C";
    break;
}