JavaScript for Beginners
About Lesson

The switch statement in JavaScript is used to perform different actions based on different conditions. It’s a great alternative to a long chain of if...else if...else statements when you have multiple conditions to check.

 

The switch Statement

The switch statement evaluates an expression and executes the block of code corresponding to the expression’s value.

Here’s an example:

let fruit = 'Apple';

switch (fruit) {
  case 'Apple':
    console.log('Apple is ₹ 32');
    break;
  case 'Banana':
    console.log('Banana is ₹ 48');
    break;
  default:
    console.log('Invalid fruit');
}

In this example, the switch statement checks the value of fruit. If fruit is 'Apple', it logs ‘Apple is ₹ 32’. If fruit is 'Banana', it logs ‘Banana is ₹ 48’. If fruit is neither 'Apple' nor 'Banana', it logs ‘Invalid fruit’.

 

The break Keyword

The break keyword is used to prevent the “fallthrough” behavior of switch statements, where all cases are evaluated until a break is encountered or the switch statement ends. If break is omitted, the switch statement will continue testing all other case statements after a match is found.

 

The default Keyword

The default keyword specifies the code to run if there is no case match. The default case does not have to be the last in a switch block. However, if default is not the last case in the switch block, remember to end it with a break.

 

The switch statement in JavaScript is a powerful tool for controlling the flow of your code. It allows you to execute different blocks of code based on different conditions. Understanding how to use the switch statement effectively is crucial to writing good JavaScript code.