Skip to main content

Command Palette

Search for a command to run...

JavaScript: Switch Statements

My first official Hashnode post

Updated
2 min read
JavaScript: Switch Statements

Introduction

Today I will be discussing JavaScript Switch cases, what they are, their applications and how they can be applied using real-life examples.

Definition

In JavaScript, the switch statement provides a way to execute different blocks of code depending on the value of an expression.

It provides a way to test multiple conditions and execute different code based on which condition is true Here's an example of a switch statement:

The simple code snippet above shows the application and use cases of JS Switch and how it can be applied.
In the code we declared a variable primeNumber and assigned it a value of number 1 while also declaring a variable called numbers.

In this example, the switch statement is evaluating the value of the primeNumber variable. If primeNumber is 1, the first case (case 0) will be executed and the number 3 will be logged to the console. If primeNumber is 2, the default case will be executed and the message "Invalid" will be logged to the console. The break keyword is used to exit the switch statement once a condition is met.

Note: The default statement doesn't have to be at the end of the code, in fact, it can be placed anywhere between the code and it will still run irrespective of its position as long as the necessary conditions are met, here is an example:

So far, Switch statements are just one of many numerous ways of executing blocks of codes precisely based on conditions being true or met using cases.

O
Obinna MH3y ago

Well done bro