JavaScript Tutorial

Javascript Switch

In JavaScript, the switch statement is used to perform different actions based on different conditions. It provides a way to select one of many code blocks to be executed.

Syntax:-

Let’s see the simple example of switch statement in javascript.

Input:-

Output:-

Right now it is not checking the condition mentioned in the switch statement, it is only executing the last statement. To overcome this situation, we have a break keyword.

Break keyword

The break keyword is used to exit the execution inside a switch block. It allows you to stop the execution of code within a specific case and prevents fall-through to the next case.

It's important to note that the break statement is not required for the last case in a switch block. The block naturally ends there, so the break statement is not necessary.

Input:-

Output:-

Default keyword

If no case is matched from the given switch conditions, the control falls to a default statement to be executed.

Input:-

Output:-

Grouping of cases

Multiple cases that have the same code can be grouped together in JavaScript. This allows you to specify a single block of code to be executed for multiple case values. By omitting the break statement after each case, the execution will flow through to the next case.

Input:-

Output:-


Go back to Previous Course