- ES6 Tutorial
- ES6 - Home
- ES6 - Overview
- ES6 - Environment
- ES6 - Syntax
- ES6 - Variables
- ES6 - Operators
- ES6 - Decision Making
- ES6 - Loops
- ES6 - Functions
- ES6 - Events
- ES6 - Cookies
- ES6 - Page Redirect
- ES6 - Dialog Boxes
- ES6 - Void Keyword
- ES6 - Page Printing
- ES6 - Objects
- ES6 - Number
- ES6 - Boolean
- ES6 - Strings
- ES6 - Symbol
- ES6 - New String Methods
- ES6 - Arrays
- ES6 - Date
- ES6 - Math
- ES6 - RegExp
- ES6 - HTML DOM
- ES6 - Iterator
- ES6 - Collections
- ES6 - Classes
- ES6 - Maps And Sets
- ES6 - Promises
- ES6 - Modules
- ES6 - Error Handling
- ES6 - Object Extensions
- ES6 - Reflect API
- ES6 - Proxy API
- ES6 - Validations
- ES6 - Animation
- ES6 - Multimedia
- ES6 - Debugging
- ES6 - Image Map
- ES6 - Browsers
- ES7 - New Features
- ES8 - New Features
- ES9 - New Features
- ES6 Useful Resources
- ES6 - Quick Guide
- ES6 - Useful Resources
- ES6 - Discussion
ES6 - switch…case Statement
The switch statement evaluates an expression, matches the expression’s value to a case clause and executes the statements associated with that case.
Following is the syntax.
switch(variable_expression) { case constant_expr1: { //statements; break; } case constant_expr2: { //statements; break; } default: { //statements; break; } }
The value of the variable_expression is tested against all cases in the switch. If the variable matches one of the cases, the corresponding code block is executed. If no case expression matches the value of the variable_expression, the code within the default block is associated.
The following rules apply to a switch statement −
- There can be any number of case statements within a switch.
- The case statements can include only constants. It cannot be a variable or an expression.
- The data type of the variable_expression and the constant expression must match.
- Unless you put a break after each block of code, the execution flows into the next block.
- The case expression must be unique.
- The default block is optional.
Flowchart
Example: switch…case
var grade="A"; switch(grade) { case "A": { console.log("Excellent"); break; } case "B": { console.log("Good"); break; } case "C": { console.log("Fair"); break; } case "D": { console.log("Poor"); break; } default: { console.log("Invalid choice"); break; } }
The following output is displayed on successful execution on the above code.
Excellent
The example verifies the value of the variable grade against the set of constants (A, B, C, D, and E) and executes the corresponding blocks. If the value in the variable doesn’t match any of the constants mentioned above, the default block will be executed.