JavaScript Switch Statements

Huda Yousif
3 min readNov 29, 2020

Switch statements are very similar to if-else and else-if statement. However a switch statement is what programmers use when there is a lot of data that they want to check for.

The switch statement is evaluated once. The value of the statement is compared with each value of the each case. Once the statement is matched the code will be executed. However, if there is no match the default code will be executed.

In the example below we’ll ask a user for their name. For the switch statement we’ll put the name inside of the parentheses. Depending on the value of the name we’ll put different things.

For example, we can have the case where the name is Sam. Once the code is run and the statement is matched, it will run the code under that block which goes in-between case label and the break statement. In this case it is Welcome Home. This essentially prevents fall through.

Now if there is another case, for example if the users name is Samantha it would display Sorry, try again in the console followed by another break.

Below you’ll see a catch all statement that I added. If the users name isn’t Sam or Samantha then we’ll have a case for that. This is known as the default case. Default is not required but it is recommended.

If the users name is Sam we will see Welcome Home in the console.

If the users name if Samantha Sorry, try again in the console.

And lastly if anything else is entered, We’ve missed you will pop up in the console.

The break prevents fall through. If we get rid of it the first break, in the example, both cases will be executed even though it doesn’t really make sense. Both Welcome Home and Sorry, try again will be displayed in the console. The break is important because it prevents this issue. The break on the default cane be removed. The code will work just fine. But as a general rule of thumb, it’s best practice to keep it.

thanks for reading!

--

--