Home  >  Article  >  Web Front-end  >  Can Multiple Cases Be Defined in a Switch Statement in JavaScript?

Can Multiple Cases Be Defined in a Switch Statement in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-10-23 22:12:30194browse

Can Multiple Cases Be Defined in a Switch Statement in JavaScript?

Using the Switch Statement for Multiple Cases in JavaScript

In JavaScript, it's not possible to define multiple cases for a switch statement in the manner described, where cases such as "afshin", "saeed", and "larry" would all trigger the same action. However, there is a technique known as "case falling through" that can be used as an alternative.

Case Falling Through

The switch statement in JavaScript supports "case falling through," a feature that enables the code in a matched case to continue execution until a break statement is encountered or the end of the switch statement is reached. By leveraging this feature, it's possible to define multiple cases that share the same execution block:

<code class="javascript">switch (varName) {
  case "afshin":
  case "saeed":
  case "larry":
    // Code that applies to all three cases
    alert("Hey");
    break;

  default:
    // Default case
    alert("Default case");
}</code>

In this example, when varName matches any of the specified cases ("afshin", "saeed", or "larry"), the "Hey" alert will be displayed. If the value of varName doesn't match any case, the default case will be executed, resulting in the "Default case" alert.

This approach adheres to the DRY (Don't Repeat Yourself) concept by defining the code that applies to multiple cases only once.

The above is the detailed content of Can Multiple Cases Be Defined in a Switch Statement in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn