Conditional Statements (Switch)…30daysofjavascript => Day 4

Olajide Blessing Niniola
2 min readMar 7, 2021

A switch statement is a type of condition in JavaScript that is used when there are multiple if-else statements, it is used to perform different actions based on different conditions and selects one of many code blocks to be executed.

The switch syntax uses the case blocks although there is an optional default case.

switch syntax
simple switch statement

The above example shows sentences to appear on the screen when the user chooses a particular pet. If the user chooses ‘hedgehog’ it logs ‘Fantastic choice’ and if the user inputs another word other than a pet, the user gets ‘not a pet’. Now, let’s look at other examples such as arithmetic operations:

operations with switch

Simple to complex operations can be performed with the switch statement. But have you thought of what could happen without the break? Let us take a look.

Switch statement without a break statement

All block codes are executed without checks, in other words, JavaScript breaks out of the switch block when it reaches the switch. This stops the execution inside the switch block.

What to remember

  • 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.
  • If there is no match, the default code block is executed.

--

--