It’s time to switch it up!

iYamSnaxx
2 min readJan 15, 2024

--

While learning JavaScript with Codecademy we learned about the switch statements. First, what is a switch statement in JavaScript? Why is it important?

Switch statements provide a means of checking an expression against multiple case clauses. If a case matches, the code inside that clause is executed.

For example, let's take a look at a simple switch.

const food = 'salad';

switch (food) {
case 'oyster':
console.log('The taste of the sea 🦪');
break;
case 'pizza':
console.log('A delicious pie 🍕');
break;
default:
console.log('Enjoy your meal');
}

Breaking this down —

  1. The variable food is assigned the value 'salad'. This could have been any random food — but I chose to pick salad for this block.
  2. The switch statement evaluates the expression food. It then checks each case against the value food to find a match.
  3. In this example, there are two cases: 'oyster' and 'pizza'. However, the value of food is 'salad', and there is no matching case. Therefore, the code inside the switch statement does not execute any of the case blocks.
  4. Since there is no matching case it then goes to the default case provided which says 'Enjoy your meal', the switch statement does nothing, and the program continues with the code following the switch statement.

Why would we want to utilize a switch statement? CLARITY and READABILITY! It makes it much more clean as opposed to other formats. Even a novice reader and writer of code like me can much more easily read how each step is completed.

Truly an interesting concept — the switch statements are how I created the Magic 8 Ball project which will be my next write-up! Here is the project below if you want a more visual option!

--

--

No responses yet