switch statement !case js code example
Example 1: js switch case
switch(expression) {
case x:
break;
case y:
break;
default:
}
Example 2: switch case in javascript
function whatToDrink(time){
var drink ;
switch (time) {
case "morning":
drink = "Tea";
break;
case "evening":
drink = "Shake";
break;
default:
drink="Water";
}
return drink;
}
console.log(whatToDrink("morning"))
console.log(whatToDrink("evening"))
console.log(whatToDrink("night"))
console.log(whatToDrink("daytime"))
Example 3: switch statement javascript
function caseInSwitch(val) {
var answer = "";
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;
}
return answer;
}
caseInSwitch(1);
Example 4: 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";
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;
}
Example 5: switch javascript
switch (expressão) {
case valor1:
[break;]
case valor2:
[break;]
...
case valueN:
[break;]
default:
[break;]
}
Example 6: javascript switch
var color = "yellow";
var darkOrLight="";
switch(color) {
case "yellow":case "pink":case "orange":
darkOrLight = "Light";
break;
case "blue":case "purple":case "brown":
darkOrLight = "Dark";
break;
default:
darkOrLight = "Unknown";
}