📜  switch case js - Javascript (1)

📅  最后修改于: 2023-12-03 14:47:48.622000             🧑  作者: Mango

Switch Case in JavaScript

Introduction

Switch case is a control statement in JavaScript that provides a way to execute different sets of code based on the value of a condition. It is a useful alternative to using a long series of if-else statements.

Syntax

The switch statement syntax is as follows:

switch (expression) {
  case value1:
    // code block 1
    break;
  case value2:
    // code block 2
    break;
  ...
  case valueN:
    // code block N
    break;
  default:
    // default code block
}
  • expression is the value to compare against in each case.
  • case valueN is a specific value to compare the expression against.
  • default is optional and executed if none of the case values match the expression.

Each case block can contain any valid JavaScript statement(s). The break statement is used to exit the switch statement once a case is executed.

Example
switch (dayOfWeek) {
  case 0:
    console.log("Sunday");
    break;
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  case 3:
    console.log("Wednesday");
    break;
  case 4:
    console.log("Thursday");
    break;
  case 5:
    console.log("Friday");
    break;
  case 6:
    console.log("Saturday");
    break;
  default:
    console.log("Invalid day of week");
}

In this example, the dayOfWeek variable is compared to a set of numeric values. If the value matches one of the cases, the corresponding day of the week is logged to the console. If none of the cases match, the default code block is executed.

Benefits

Using switch case can help make your code more concise and easier to read. It also helps avoid the pitfalls of nested if-else statements.

Some scenarios in which switch case can be used include:

  • Handling user input
  • Parsing API responses
  • Handling errors or exceptions
Conclusion

Switch case is a useful control statement in JavaScript that provides an alternative to using long if-else statements. It is useful for handling user input, parsing API responses, or handling different error conditions.