Using the Switch Statement in Javascript

Susanne Lundkvist
2 min readJun 9, 2019

--

When you have multiple if statement, using switch might be simpler (flickr).

Sometimes when you’ve written an if statement in JS you realise you need another one. And then another one. Instead of writing multiple if statements you can use switch, which is a more descriptive way to compare a value with multiple variants.

The switch has one or more case blocks and an optional default. This is what the syntax looks like:

switch(x) {
case 'value1': // if (x === 'value1')
...
[break]

case 'value2': // if (x === 'value2')
...
[break]

default:
...
[break]
}
  • The value of x is checked for strict equality to the value from the first case (value1) then to the second (value2) etc.
  • If equality is found, switch will execute the code, starting from the corresponding case, until the nearest break (or until the end of switch).
  • If no case is matched then the default code is executed (if you have chosen to have a default option).

The following example uses the weekday number to calculate the weekday name. The getDay() method returns a number between 0 and 6, each representing a specific weekday (Sunday = 0, Monday = 1 etc).

The break has to be there for the code to stop executing or else it will carry on as in the following example:

In this example the result would be the following, because break is missing:

Susanne Lundkvist

--

--

Susanne Lundkvist

Product and Programme Manager, coding in Ruby on Rails, JavaScript/React and Python. Improving product and project management with data analytics.