Switch
The switch
statement evaluates an expression and allows different blocks of code to execute depending on the result of that expression. It contains any number of case
clauses marking code to execute based on values returned by the expression, and an optional default
statement marking code that executes if none of the case
clauses are true.
The code following a matching case
clause will execute until it encounters a break
statement, a return
statement, or the end of the switch
block.
This means that if a break
is omitted at the end of one case
block, subsequent case
blocks and/or the default
block will be executed regardless of the value of the original expression.
Syntax
switch (expression) {case value1:// Statements executed when expression = value1break;case value2:// Statements executed when expression = value2break;case value3:// Statements executed when expression = value3break;default:// Statements executed when expression not equal to value1, value2 or value3}
With break
statements omitted:
switch (expression) {case value1:// Statements executed when expression = value1case value2:// Statements executed when expression = value2 or value1case value3:// Statements executed when expression = value3, value2 or value1default:// Statements always executed}
Example
Determine whether a rating
is a 5, 4, 3, or something else:
switch (rating) {case 5:console.log('Excellent 👏');break;case 4:console.log('Good 👍');break;case 3:console.log('Fair 👌');break;default:console.log('Poor 👎');}
- If
rating
is 5, print"Excellent 👏"
. - If
rating
is 4, print"Good 👍"
. - If
rating
is 3, print"Fair 👌"
. - Else, print
"Poor 👎"
.
Codebyte Example
Here, an expression is used to find whether a number is even, odd, or not a number:
All contributors
- christian.dinh
- Anonymous contributor
- StevenSwiniarski
- Anonymous contributor
- THE-Spellchecker
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Skill path
Create a Back-End App with JavaScript
Learn how to build back-end web APIs using Express.js, Node.js, SQL, and a Node.js-SQLite database library.Includes 8 CoursesWith CertificateBeginner Friendly30 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours