-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
In JavaScript, the switch statement is an alternative to using multiple if...else if statements when you need to compare a single expression against multiple possible values. It provides a cleaner and more readable way to handle conditional logic when there are many possible cases. Understanding switch statements is essential for writing organized, efficient, and maintainable code, especially in scenarios with numerous discrete options.
This tutorial explains the syntax, use cases, practical examples, common mistakes, and best practices for using switch statements effectively.
The switch statement is particularly useful because it:
Offers a cleaner alternative to multiple if...else if statements.
Improves readability for cases with many conditions.
Helps organize code logically based on discrete values.
Reduces the chance of errors when checking a single variable against multiple values.
Makes maintenance and updates easier as your conditions grow.
For instance, you might use switch to display the day of the week, determine user roles, select menu actions, or implement different behaviors based on input values.
The syntax of a switch statement is:
switch (expression) {
case value1:
// Code to execute if expression === value1
break;
case value2:
// Code to execute if expression === value2
break;
default:
// Code to execute if no cases match
}
expression is evaluated once and compared against each case value.
The break statement prevents the execution from “falling through” to subsequent cases.
The default case is optional and executes if none of the cases match.
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
case 4:
console.log("Thursday");
break;
case 5:
console.log("Friday");
break;
case 6:
console.log("Saturday");
break;
case 7:
console.log("Sunday");
break;
default:
console.log("Invalid day");
}
In this example, day is compared against each case. Since day equals 3, the output will be Wednesday. The break ensures that only the matching case executes.
Sometimes, multiple cases should execute the same block of code. You can group them:
let color = "blue";
switch (color) {
case "red":
case "pink":
console.log("The color is red or pink");
break;
case "blue":
case "green":
console.log("The color is blue or green");
break;
default:
console.log("Unknown color");
}
Here, both "blue" and "green" result in the same output. This technique avoids duplicate code and improves readability.
switch can handle expressions or conditions by using true as the expression:
let score = 85;
switch (true) {
case score >= 90:
console.log("Grade A");
break;
case score >= 75:
console.log("Grade B");
break;
case score >= 50:
console.log("Grade C");
break;
default:
console.log("Fail");
}
By using switch(true), each case can be a conditional expression. This approach is useful when comparing ranges of values.
let day = 5;
switch(day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
case 4:
console.log("Thursday");
break;
case 5:
console.log("Friday");
break;
case 6:
console.log("Saturday");
break;
case 7:
console.log("Sunday");
break;
default:
console.log("Invalid day");
}
let option = "save";
switch(option) {
case "open":
console.log("Opening file...");
break;
case "save":
console.log("Saving file...");
break;
case "close":
console.log("Closing file...");
break;
default:
console.log("Unknown option");
}
let marks = 82;
switch(true) {
case marks >= 90:
console.log("Grade A");
break;
case marks >= 75:
console.log("Grade B");
break;
case marks >= 50:
console.log("Grade C");
break;
default:
console.log("Fail");
}
let fruit = "apple";
switch(fruit) {
case "apple":
case "pear":
console.log("This is a fruit");
break;
case "carrot":
case "broccoli":
console.log("This is a vegetable");
break;
default:
console.log("Unknown food");
}
let dayNumber = 6;
switch(dayNumber) {
case 6:
case 7:
console.log("It's the weekend!");
break;
default:
console.log("It's a weekday");
}
Forgetting the break statement, causing fall-through behavior.
Omitting the default case, which leaves unmatched values unhandled.
Using complex expressions directly in the switch expression instead of true.
Relying on type coercion, since switch uses strict equality (===) for comparisons.
Always include break unless fall-through is intentional.
Use default to handle unexpected values.
Keep cases simple and readable; avoid complex logic inside cases.
Consider if...else for range checks or complex conditions.
Group cases that should execute the same code to reduce duplication.
Menu or action selection in applications
Routing logic based on user input
Handling different user roles and permissions
Implementing a grading or scoring system
Mapping numeric or string codes to descriptive outputs
The switch statement in JavaScript is a powerful tool for handling multiple conditional branches in a clean and organized way. It simplifies code readability when compared to long chains of if...else if statements, especially when dealing with discrete values. By using break to prevent fall-through, default to handle unexpected values, and grouping cases when appropriate, developers can write maintainable, efficient, and predictable code. The switch statement is ideal for menu selections, user roles, grading systems, and any scenario where a single variable needs to be checked against multiple possible outcomes.
Q1. How do you write a switch statement to check for 3 possible grades (A, B, C)?
Q2. What is the purpose of the break statement inside a switch block?
Q3. How do you use the default case in a switch statement?
Q4. Can multiple case labels execute the same code block in a switch?
Q5. What will happen if you forget to use break in a switch block?
Q6. How do you match a variable against 5 possible values using switch?
Q7. Can you use expressions like x > 5 inside a case label?
Q8. How do you check for both "Saturday" and "Sunday" as weekends in one case block?
Q9. What does JavaScript do if none of the case values match and there is no default block?
Q10. Write a switch that prints the name of a month based on its number (1–12).
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
