Switch Statement-tutorial
In JavaScript, the switch statement is used to execute different blocks of code based on the value of an expression.
It is especially useful when you have many possible values to compare against instead of writing multiple if...else if statements.
Syntax:
It is especially useful when you have many possible values to compare against instead of writing multiple if...else if statements.
Syntax:
switch (expression) { case value1: // Code to run if expression === value1 break; case value2: // Code to run if expression === value2 break; // Add more cases as needed default: // Code to run if no case matches}
- expression: The value you want to test.
- case: Each possible match.
- break: Stops further checking once a match is found.
- default: Runs if none of the cases match.
Example:
<!DOCTYPE html><html>
<body> <script> var grade = 'B'; var result;
switch (grade) { case 'A': result = "A Grade"; break; case 'B': result = "B Grade"; break; case 'C': result = "C Grade"; break; default: result = "No Grade"; }
document.write(result); </script></body>
</html>
Output
.webp)
Why Use switch ?
- Makes code cleaner and easier to read than multiple if...else if blocks.
- Best used when comparing the same variable or expression to many values.
- Helps organize code for menu selections, grades, options, etc.