From the course: Learn JavaScript: Write Modern Code with JavaScript ESNext

Unlock this course with a free trial

Join today to access over 25,000 courses taught by industry experts.

Learn about switch-case blocks in JavaScript

Learn about switch-case blocks in JavaScript

- Somewhat related to the if else statements we talked about earlier in the course, JavaScript also provides us with something called a switch case statement. This is something that's used when our program is faced with a range of possible values for a given variable, and we want it to behave differently depending on which of those values it is. For example, let's say that the user had to answer a multiple choice question with possible answers A, B, C, and D. Based on the response, we could give them individualized answers using an if statement with a lot of else if blocks like this, but that's a little more verbose than it could be. So this is where JavaScript steps in and says, "Hold on, I have a much cleaner way for you to write that." And that's using the switch case statement. So here's what the switch case statement would look like for this example, we'd start off with the switch keyword and the variable we want to look at. In this case, we're using a variable called userAnswer.…

Contents