🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › switch
switch - JavaScript - MDN Web Docs - Mozilla
switch (true) { case isSquare(shape): console.log("This shape is a square."); // Fall-through, since a square is a rectangle as well! case isRectangle(shape): console.log("This shape is a rectangle."); case isQuadrilateral(shape): console.log("This shape is a quadrilateral."); break; case isCircle(shape): console.log("This shape is a circle."); break; } ... This page was last modified on Jul 8, 2025 by MDN contributors.
🌐
Unibo
lia.disi.unibo.it › materiale › JS › developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › switch.html
switch - JavaScript | MDN
The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.
Discussions

Javascript operators in switch case - Stack Overflow
I'm creating a panel and there are stats for memory, CPU and HDD. I'm using a switch statement and in the case method, I'm putting the current usage of CPU, memory and HDD. However, the problem is... More on stackoverflow.com
🌐 stackoverflow.com
'switch' statement: using 'default' between cases
Your default case should be the last one. It's the equivalent of "else" in an "if" statement. The explanation is that the cases are checked from top to bottom. When it gets to the default case, default matches anything and so it logs "default". However, because there is no break, the way switch works is that it just moves on to the next case block and executes it (without performing the check). This isn't the result of the default, it's the result of there being no "break". I can understand why you have omitted the break (because otherwise the final case would never be evaluated) but that's why default needs to go at the end. It's the thing that is executed when all the other cases have failed. More on reddit.com
🌐 r/learnjavascript
2
3
June 26, 2022
Issue with "switch": …
MDN URL: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch What information was incorrect, unhelpful, or incomplete? In the "Methods for multi-criteria case" section it starts with "Source for this techn... More on github.com
🌐 github.com
3
January 10, 2021
Expression inside switch case statement
I'm trying to create a switch statement but I can't seem to be able to use an expression that gets evaluated (rather than a set string/integer). I can easily do this with if statements but case sho... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
github.com › mdn › content › blob › main › files › en-us › web › javascript › reference › statements › switch › index.md
content/files/en-us/web/javascript/reference/statements/switch/index.md at main · mdn/content
The switch statement evaluates an expression, matching the expression's value against a series of case clauses, and executes statements after the first case clause with a matching value, until a break statement is encountered.
Author   mdn
🌐
Mozilla
interactive-examples.mdn.mozilla.net › pages › js › statement-switch.html
JavaScript Demo: Statement - Switch - Mozilla
const expr = 'Papayas'; switch (expr) { case 'Oranges': console.log('Oranges are $0.59 a pound.'); break; case 'Mangoes': case 'Papayas': console.log('Mangoes and papayas are $2.79 a pound.'); // Expected output: "Mangoes and papayas are $2.79 a pound." break; default: console.log(`Sorry, we ...
🌐
X
x.com › MozDevNet › status › 1899807663476932642
switch - JavaScript | MDN
March 12, 2025 - MDN Web Docs · @MozDevNet · The switch statement is a cleaner, more readable way to handle multiple conditions in JavaScript. Use it for, ✔️ Comparing a single variable to multiple values ✔️ Handling many cases without deep nesting ...
🌐
Seanbarry
seanbarry.dev › posts › switch-true-pattern
Using the Switch(true) Pattern in JavaScript - Seán Barry
April 11, 2021 - In this example, the expression (city variable) is matched against each case in the switch statement.
🌐
Medium
medium.com › @elainaseki › things-i-dont-know-about-javascript-switch-statement-f84e20ec3132
Things I didn’t know about Javascript switch statements | by Elaina Shi | Medium
April 25, 2019 - If I lookup the documentation on MDN web docs, I will find the definition of switch statement : “The switch statement evaluates an expression, matching the expression’s value to a case clause, and executes statements associated with that case, as well as statements in cases that follow the matching case.”
🌐
ThisCodeWorks
thiscodeworks.com › 61808013394cdf00159f027e
switch - JavaScript | MDN | thiscodeWorks
/* function functionName(condition) { switch(condition) { case value1 : Statement1 case value2 : Statement2 default : Statement3 } } */ function isRose(cat) { switch(cat) { case 'rose' : return 'Hi, Rose!' case 'ted' : return 'Hi, Ted!' default : return `Hi, ${cat}!` } } content_copyCOPY https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
Find elsewhere
🌐
Can I Use
caniuse.com › mdn-javascript_statements_switch
JavaScript statement: switch | Can I use... Support tables for HTML5, CSS3, etc
"Can I use" provides up-to-date browser support tables for support of front-end web technologies on desktop and mobile web browsers.
🌐
MDN Web Docs
devdoc.net › web › developer.mozilla.org › en-US › docs › JavaScript › Reference › Statements › switch.html
switch - JavaScript | MDN - Documentation
June 20, 2017 - The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.
🌐
Stack Overflow
stackoverflow.com › questions › 50455138 › javascript-operators-in-switch-case
Javascript operators in switch case - Stack Overflow
MDN has an excellent resources on comparison operators. ... Sign up to request clarification or add additional context in comments. ... Thanks, i correct the operator for 80+% using Chase DeAnda method. 2018-05-21T20:39:44.973Z+00:00 ... Save this answer. ... Show activity on this post. Created a getClassName method that accepts a percent and will return a className: Copyconst getClassName = percent => { switch(true){ case (percent <= 0.01): return 'progress-bar-primary'; case (percent <= 33): return 'progress-bar-success'; case (percent <= 66): return 'progress-bar-warning'; case (percent <= 80): return 'progress-bar-danger'; default: return 'progress-bar-theme'; } } console.log('0: ', getClassName(0)); console.log('40: ', getClassName(40)); console.log('50: ', getClassName(50)); console.log('80: ', getClassName(80)); console.log('100: ', getClassName(100));
🌐
Reddit
reddit.com › r/learnjavascript › 'switch' statement: using 'default' between cases
r/learnjavascript on Reddit: 'switch' statement: using 'default' between cases
June 26, 2022 -

MDN - The switch statement

I'm trying to understand the example provided by MDN for putting default between cases in a switch statement. I even used a code visualizer but still don't understand the explanation offered--why does it log "default" and surprisingly "1" as well.

Top answer
1 of 2
5
Your default case should be the last one. It's the equivalent of "else" in an "if" statement. The explanation is that the cases are checked from top to bottom. When it gets to the default case, default matches anything and so it logs "default". However, because there is no break, the way switch works is that it just moves on to the next case block and executes it (without performing the check). This isn't the result of the default, it's the result of there being no "break". I can understand why you have omitted the break (because otherwise the final case would never be evaluated) but that's why default needs to go at the end. It's the thing that is executed when all the other cases have failed.
2 of 2
4
Two things to keep in mind. 1. When there's no match, the default clause will run irrespective of where it's placed. The page you have linked explains it here: Can I put a default between cases? Yes, you can! JavaScript will drop you back to the default if it can't find a match. It also works when you put default before all other cases. 2. When a break is missing, the execution falls through to the next case and executes that clause even if the case is not satisfied. This fall through happens until a break is present or switch closing brace is reached. default: console.log('default') // fall-through case 1: console.log('1'); In the MDN code, foo is 5 and hence the default clause runs, but after console.log runs, there's no break to stop execution and hence case 1 clause is also run, resulting in both "default" and "1" getting logged. If we add a break where // fall-through is there, then only "default" will get logged.
🌐
GitHub
github.com › mdn › translated-content › blob › main › files › fr › web › javascript › reference › statements › switch › index.md
translated-content/files/fr/web/javascript/reference/statements/switch/index.md at main · mdn/translated-content
Si cette clause optionnelle n'est pas utilisée, le programme continue son exécution après l'instruction `switch`. Par convention, la clause `default` est utilisée en dernière mais cela n'est pas nécessaire. ... L'instruction {{jsxref("Instructions/break","break")}} peut optionnellement être utilisée pour chaque cas et permet de s'assurer que seules les instructions associées à ce cas seront exécutées.
Author   mdn
🌐
GitHub
github.com › mdn › content › issues › 1142
Issue with "switch": … · Issue #1142 · mdn/content
January 10, 2021 - MDN URL: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch What information was incorrect, unhelpful, or incomplete? In the "Methods for multi-criteria case&q...
Author   mdn
🌐
Syntaxdb
syntaxdb.com › ref › javascript › switch
Switch Case in JavaScript - SyntaxDB - JavaScript Syntax Reference
var choice = 'Y'; switch(choice) { case 'Y' : console.log("Yes"); break; case 'M' : console.log("Maybe"); break; case 'N' : console.log("No"); break; default: console.log("Invalid response"); }
🌐
W3Schools
w3schools.com › js › js_switch.asp
JavaScript Switch Statement
JS Examples JS HTML DOM JS HTML ... Plan JS Interview Prep JS Bootcamp JS Certificate ... Based on a condition, switch selects one or more code blocks to be executed....
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements
Statements and declarations - JavaScript - MDN Web Docs
Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
Top answer
1 of 8
173

amount is a number, but the expressions in the case clauses only evaluate to booleans; the values will never match.

You could always do

switch (true) {
  case (amount >= 7500 && amount < 10000):
    // Code
    break;
  case (amount >= 10000 && amount < 15000):
    // Code
    break;
  // etc.
}

It works because the value being matched is now the boolean true, so the code under the first case clause with an expression that evaluates to true will be executed.

It’s kinda “tricky”, I guess, but I see nothing wrong with using it. A simple ifelse statement would probably be more concise, and you’d not have to worry about accidental fall-through. But there it is anyway.

2 of 8
17

@MooGoo's switch (true) will give you a Weird condition error in jsLint, so let's get a little more creative in case that's an issue, and, I think, increase readability a touch.

So we're not evaluating if each case is true or false; we're comparing if that case's value is equal to our switch term. So let's take advantage of that by throwing a shorthand if into our case statement and return our original switch term if the condition's true.

I'm also including a sort of real world example, where you want to have two "defaults" -- one if your term is outside of your "important" range in the positive direction, and another in case you're in the negative direction.

Key phrase: case (x > 0 ? x : null):

"If my term, x, is greater than zero, return x so that x === x and I take the case branch."

http://jsfiddle.net/rufwork/upGH6/1/

/*global document*/
/*jslint evil:true*/
var x = 10;

switch (x) {
    case (x > 0 ? x : null):
        document.write('ha ha ha!  I fooled switch AND jsLint!  Muhahahahaha!');
        break;
    case 0:
        document.write('zero is nothing.');
        break;
    case -1:
        document.write('low');
        break;
    case -2:
        document.write('lower');
        break;
    case -3: 
        document.write('lowest I care about');
        break;
    default: // anything lower than -3.
        document.write('TOO LOW!!!! (unless you cheated and didn\'t use an int)');
}
document.write('<br>done.');

Quick reply to @Sv443:

Do notice that the default: switch says, "unless you cheated and didn't use an int" and that short circuiting requires x === x when you return x.

But your point is a useful reminder that NaN is the only case where short circuiting can't apply.

That is, x must == x to short circuit in switch and, as MDN tells us, "NaN, and only NaN, will compare unequal to itself" (double or triple =).

That also means that switching on a NaN value (and only a NaN value) will always hit default in ANY switch because you can't match its value.

Here's the full quote from MDN:

NaN compares unequal (via ==, !=, ===, and !==) to any other value -- including to another NaN value. Use Number.isNaN() or isNaN() to most clearly determine whether a value is NaN. Or perform a self-comparison: NaN, and only NaN, will compare unequal to itself.

You could change the default logic to check what you have:

isNaN(x) ? document.write ('nan') : document.write('TOO LOW!!!! ...)');

Or you even could go full hipster like MDN suggests (but please don't ;^D):

x !== x ? document.write ('nan') : document.write('TOO LOW!!!! ...)');