Our first switch statement will test different conditions to see what day of the week it is today.
The switch statement will do this by utilizing a JavaScript date object, which will be covered in a later segment.
The variables ‘today’ and ‘day’ get the current date from the JavaScript Date object. Objects are covered in a later segment. The value of the day is returned to us in a numeric format, with 0 representing Sunday, 1 representing Monday, and so on.
We use a switch statement instead of seven if, else if, else statements to determine what day it is.
The variable day is compared to the values of each case. When the value is matched, the day is printed.
We always include a default statement in switch statements in case of an error on our part, or in case none of the cases evaluate as true.
The default case also helps with troubleshooting instead of not having any output when something goes wrong.
See the Pen 3.2 Example by LSU DDEM (@lsuddem) on CodePen.
This switch example determines the letter grade of a test score out of 100
let testScore = 73;
// Note that we use 'true' in place of the tested variable, and incorporate the testScore variable in the case conditions
switch(true){
case testScore >= 90:
console.log(testScore +" / 100 : A");
break;
case testScore >= 80:
console.log(testScore +" / 100 : B");
break;
case testScore >= 70:
console.log(testScore +" / 100 : C");
break;
case testScore >= 60:
console.log(testScore +" / 100 : D");
break;
case testScore >= 50:
console.log(testScore +" / 100 : F");
break;
default:
console.log("Score is too low to even have a grade");
}
See the Pen Exercise 3.2 by LSU DDEM (@lsuddem) on CodePen.