0
0
Javascriptprogramming~5 mins

Switch statement in Javascript

Choose your learning style9 modes available
Introduction

A switch statement helps you choose between many options easily. It makes your code cleaner when you check one value against many cases.

When you want to run different code based on a single variable's value.
When you have many conditions to check instead of many if-else statements.
When you want your code to be easier to read and organize choices clearly.
When you want to handle menu selections or commands based on user input.
When you want to group similar actions under one variable check.
Syntax
Javascript
switch (expression) {
  case value1:
    // code to run if expression === value1
    break;
  case value2:
    // code to run if expression === value2
    break;
  // more cases...
  default:
    // code to run if no case matches
    break;
}

The break stops the switch from running the next cases.

The default case runs if no other case matches.

Examples
This checks the value of day and prints a message for Monday, Friday, or any other day.
Javascript
switch (day) {
  case 'Monday':
    console.log('Start of the week');
    break;
  case 'Friday':
    console.log('Almost weekend');
    break;
  default:
    console.log('Just another day');
    break;
}
Multiple cases can share the same code, like blue and green here.
Javascript
let color = 'red';
switch (color) {
  case 'blue':
  case 'green':
    console.log('Cool color');
    break;
  case 'red':
    console.log('Warm color');
    break;
  default:
    console.log('Unknown color');
    break;
}
Sample Program

This program checks the fruit and prints its color category.

Javascript
const fruit = 'apple';
switch (fruit) {
  case 'banana':
    console.log('Yellow fruit');
    break;
  case 'apple':
    console.log('Red or green fruit');
    break;
  case 'orange':
    console.log('Orange fruit');
    break;
  default:
    console.log('Unknown fruit');
    break;
}
OutputSuccess
Important Notes

Always use break to avoid running code in the next cases unintentionally.

The default case is optional but useful for unexpected values.

Switch works best with simple values like strings or numbers.

Summary

Switch helps pick code to run based on one value.

Use case for each option and break to stop.

default runs if no case matches.