Home > Web Front-end > JS Tutorial > body text

Can You Use Expressions in Switch Case Statements in JavaScript?

Linda Hamilton
Release: 2024-10-31 20:27:02
Original
137 people have browsed it

Can You Use Expressions in Switch Case Statements in JavaScript?

Expression Evaluation in Switch Case Statements

When crafting switch statements in programming, you might encounter situations where you desire to utilize expressions within case clauses instead of fixed values. While if statements readily accommodate such expressions, concerns arise about the potential efficiency of switch statements in such scenarios.

Consider the following JavaScript code:

<code class="javascript">function reward(amount) {
    var $reward = $("#reward");
    switch (amount) {
        case (amount >= 7500 && amount < 10000):
            $reward.text("Play Station 3");
            break;
        case (amount >= 10000 && amount < 15000):
            $reward.text("XBOX 360");
            break;
        case (amount >= 15000):
            $reward.text("iMac");
            break;
        default:
            $reward.text("No reward");
            break;
    }
}</code>
Copy after login

In this example, we attempt to evaluate expressions within the case clauses. However, we face a snag because the expressions only yield boolean values, whereas the amount value we're comparing is a number. This mismatch prevents the case clauses from triggering correctly.

One viable solution is to employ an alternative syntax:

<code class="javascript">switch (true) {
  case (amount >= 7500 && amount < 10000):
    // Code
    break;
  case (amount >= 10000 && amount < 15000):
    // Code
    break;
  // etc.
}</code>
Copy after login

By introducing the true identifier, we effectively convert the expression evaluation to a comparison with the boolean true. When the expression in a case clause evaluates to true, the code within that clause will execute.

Although this technique appears slightly unconventional, it circumvents the limitations encountered when directly comparing expressions in case clauses. As a result, you can achieve the desired behavior while maintaining the efficiency advantages of switch statements.

The above is the detailed content of Can You Use Expressions in Switch Case Statements in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!