Watching:

Use Switch Statements for More Dynamic JavaScript


show more Unlike If statements, switch statements in JavaScript can be useful in situations where there are multiple conditions to be checked. Simon covers the usage of switch statements to include several cases or options to check, as well ideal use cases for using switch statements instead of if statements. show less
please wait ...

Using the switch statement

You will end up writing if statements in pretty much every program you ever write, but sometimes there's a specific situation where it's not the only option for checking a condition. Let's say you're checking a variable for a selection of very specific values. Here is what I mean by that. We create a variable in this case called grade, and somewhere in the program I want to check is it Regular or is it Premium or is it Diesel? I've got a few very specific values I'm asking for. We can do this as a series of separate self-contained if statements like I have here or we could even start using the else condition to actually start combining them altogether, but this can get a little clunky, particularly if you don't just have three or four but you have 10 or 12.

Well, in this kind of situation, JavaScript and most other languages have something called the switch statement instead of the if statement. Now in some other languages, it's called the select or selec...

Using the switch statement
Video duration: 6m 5s 4h 47m Beginner

Viewers:

Unlike If statements, switch statements in JavaScript can be useful in situations where there are multiple conditions to be checked. Simon covers the usage of switch statements to include several cases or options to check, as well ideal use cases for using switch statements instead of if statements.

Subjects:
Developer Web
Author:
please wait ...