Ad space (banner)
🟨JavaScript Lessons
Lesson 15 / 69

The switch Statement

In this lesson you'll learn how to write a switch statement in JavaScript so you can express branching on a single value more clearly than a chain of if statements. This is for people searching "JavaScript switch statement usage" or "JavaScript switch break."

A switch statement is a way to branch on a single value that's often easier to read than lining up if / else if. It's written as switch (value) { case value1: ...; break; ... default: ...; }, and the processing under whichever case matches gets executed. It's commonly used for things like picking a day of the week or choosing a menu option — deciding among a fixed set of choices.

The sample code displays a day name based on the value of the day variable. It matches case 3:, so "Wednesday" is displayed, and then break exits the switch statement. If none of the cases match, the default block runs — this plays the same role as an if statement's else.

The single most common beginner mistake is forgetting to write break. Without break, execution "falls through" from the matched case straight into the processing of the next case too. This tends to cause bugs, but it's also sometimes deliberately used when you want several cases to share the same processing — a somewhat special quirk of the language.

In real development, switch statements are commonly used to switch what's displayed or how something is processed based on a status — an order's state, or a permission level, for example. When there are three or more branch options and you can decide based on a single value, a switch statement usually communicates intent more clearly than a chain of if/else ifs.

If you want several cases to run the same processing, you can write case 1: and case 2: back to back with no code in between, letting both values run the same block (deliberately using fall-through).

You can also use strings as the value in a switch statement. Writing something like case "Monday": lets you branch on strings just as easily as numbers — a pattern often used for things like dispatching on the type of a command in real projects.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)