A switch statement is a fundamental control structure used to perform basic actions based upon different conditions passed within. In a switch case, we pass upon a condition that checks whether the state gets satisfied upon the switch block of its presence.
Syntax
switch(condition){
case
break
}
Example:
let animal = 'tiger'
switch(animal)
{
case 'tiger':
case 'lion':
case 'Dog':
console.log("Permission granted upon Noah's ark")
break;
case 'Carrot':
console.log("Not an animal")
break;
case 'chair':
default:
console.log("Not permitted inside the ark")
}
Output: Permission granted upon Noah's ark
- In this code, we have declared a variable named animal with value tiger.
- We simply tell the switch case to search for the value tiger assigned and execute that case body and break.
- This is the basic doing of a switch case. It searches among the body of the case for the tiger, and when it matches, it executes the case body and breaks out of the loop.
- If we don't use a break, the loop continues to proceed to the end.
- Now a default at the end of the code we mentioned is nothing but like an else, which is satisfied when the switch case doesn't match any of the provided variables.