javascript switch expression code example
Example 1: js switch case
switch(expression) {
case x:
break;
case y:
break;
default:
}
Example 2: 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 3: 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 4: 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 5: switch in javascript
const expr = 'Papayas';
switch (expr) {
case 'Oranges':
console.log('Oranges are $0.59 a pound.');
break;
case 'Mangoes':
case 'Papayas':
console.log('Mangoes and papayas are $2.79 a pound.');
break;
default:
console.log(`Sorry, we are out of ${expr}.`);
}
Example 6: switch javascript
switch (expressão) {
case valor1:
[break;]
case valor2:
[break;]
...
case valueN:
[break;]
default:
[break;]
}