Switch Case in JavaScript
Introduction to Switch Case in JavaScript
Switch case in JavaScript is used to handle multiple conditions in a clean and structured way. In this JavaScript tutorial for beginners, you will learn how switch case in JavaScript works and how it can replace multiple if else statements. Understanding switch case in JavaScript helps you write more readable and efficient code.
If you want to continue learning step by step, you can click here for free courses and explore the complete JavaScript tutorial.
What is Switch Case in JavaScript
Switch case in JavaScript is a conditional statement that checks a value against multiple cases. When a match is found, the corresponding block of code is executed.
Syntax of Switch Case in JavaScript
case value1:
// code block
break;
case value2:
// code block
break;
default:
// default code
}
Example of Switch Case in JavaScript
switch (day) {
case 1:
console.log(“Monday”);
break;
case 2:
console.log(“Tuesday”);
break;
case 3:
console.log(“Wednesday”);
break;
default:
console.log(“Invalid day”);
}
In this example, switch case in JavaScript checks the value of day and prints the result.
Break Statement in Switch Case
The break statement is used to stop execution after a case is matched. Without break, the program will continue executing the next cases.
Example Without Break
switch (value) {
case 1:
console.log(“One”);
case 2:
console.log(“Two”);
}
This will print both One and Two because there is no break statement.
Default Case in JavaScript
The default case runs when no matching case is found.
switch (color) {
case “red”:
console.log(“Red color”);
break;
default:
console.log(“Other color”);
}
When to Use Switch Case in JavaScript
Switch case in JavaScript is useful when you have multiple fixed values to compare. It is cleaner and easier to read than long if else statements.
Conclusion
Switch case in JavaScript is a powerful control flow statement that helps handle multiple conditions efficiently. By using switch case in JavaScript, you can improve code readability and structure.
FAQs
What is switch case in JavaScript
Switch case in JavaScript is used to execute different code blocks based on matching values.
When should I use switch instead of if else
Switch is better when you have multiple fixed conditions to check.
What is the use of break in switch case
Break stops execution after a case is matched.



