JavaScript Switch JAVASCRIPT
- JavaScript Introduction
- JavaScript Syntax
- JavaScript innerHTML
- JavaScript document.write()
- Javascript - window.alert()
- JavaScript - console.log()
- JavaScript Comments
- JavaScript Variables
- JavaScript Operators
- JavaScript Data Types
- JavaScript Functions
- JavaScript Objects
- JavaScript Events
- JavaScript Strings
- JavaScript String Methods
- JavaScript Numbers
- JavaScript Number Methods
- JavaScript Arrays
- JavaScript Array Methods
- JavaScript Sorting Arrays
- JavaScript Array Iteration
- JavaScript Date Objects
- JavaScript Date Formats
- JavaScript Get Date Methods
- JavaScript Set Date Methods
- JavaScript Math Object
- JavaScript Conditions
- JavaScript Switch
- JavaScript Loop For
- JavaScript While Loop
- JavaScript Break and Continue
- JavaScript Type Conversion
- JavaScript Errors
- JavaScript Scope
- JavaScript this Keyword
- JavaScript Classes
- JavaScript Debugging
- JavaScript - Changing CSS
- JavaScript JSON
JavaScript Switch
The JavaScript Switch Statement
Use the switch
statement to select one of many code blocks to be executed.
Syntax
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
- The switch expression is evaluated once.
- The value of the expression is compared with the values of each case.
- If there is a match, the associated block of code is executed.
The getDay() method returns the weekday as a number between 0 and 6. (Sunday=0, Monday=1, ...)
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
The break Keyword
When JavaScript reaches a break
keyword, it breaks out of the switch block.
This will stop the execution of the block.
It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway.
The default Keyword
The default
keyword specifies the code to run if there is no case match.
Example: The getDay() method returns the weekday as a number between 0 and 6.
switch (new Date().getDay()) {
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the Weekend";
}
Strict Comparison
Switch cases use strict comparison (===).
The values must be of the same type to match.
A strict comparison can only be true if the operands are of the same type.
In this example there will be no match for x:
Example
var x = "0";
switch (x) {
case 0:
text = "Off";
break;
case 1:
text = "On";
break;
default:
text = "No value found";
}