
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is Switch...case statement in JavaScript?
The objective of a switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used.
You can use a switch statement which handles exactly this situation, and it does so more efficiently than repeated if...else if statements.
Syntax
switch(expression) { case condition 1:statement(s) break; case condition 2:statement(s) break; ... case condition n:statement(s) break; default:statement(s) }
The break statements indicate the end of a particular case. If they were omitted, the interpreter would continue executing each statement in each of the following cases.
Example
You can try to run the following to learn how to work with switch case statement in JavaScript −
<html> <body> <script> var grade = 'A'; document.write("Entering switch block<br />"); switch(grade) { case'A': document.write("Good job <br />"); break; case'B': document.write("Pretty good <br />"); break; case'C': document.write("Passed <br />"); break; case'D': document.write("Not so good <br />"); break; case'F': document.write("Failed <br />"); break; default: document.write("Unknown grade<br />") } document.write("Exiting switch block"); </script> </body> </html>
- Related Questions & Answers
- Switch case statement in C
- What is a switch case statement in Java and how to use it?
- How to implement switch-case statement in Kotlin?
- Switch case calculator in JavaScript
- How to use case-insensitive switch-case in JavaScript?
- Switch case in Arduino
- Explain Strict Comparison in JavaScript switch statement?
- Java switch statement
- PHP switch Statement
- Switch Statement in Java
- Switch Case in Python (Replacement)
- Can we have a return statement in a JavaScript switch statement?
- Explain common code blocks in JavaScript switch statement?
- Please explain what happens when PHP switch case executes case 0?
- What is difference between using if/else and switch-case in C#?
Advertisements