Javascript using true as condition in switch case


I was trying this codewars challenge…

here is my solution

    switch (n) {
        case (n == Number.MAX_VALUE): return "Input number is Number.MAX_VALUE";
        case (n == Number.POSITIVE_INFINITY): return "Input number is Number.POSITIVE_INFINITY";
        case (n == Number.MIN_VALUE): return "Input number is Number.MIN_VALUE";
        case (n == Number.NEGATIVE_INFINITY): return "Input number is Number.NEGATIVE_INFINITY";
        case (isNaN(n)): return "Input number is Number.NaN";
        default: return "Input number is " + n;


//gives me the same number 1.7976931348623157e+308 rather than giving me  Number.MAX_VALUE

when i looked in to codewars solution they have used true in the switch case condition

switch(true) {


i want to know what’s happening here when the condition is true in switch case and what’s wrong with n as my condition

Please explain me


Think of the switch as the left side of an === and the case as the right side. You’ve put n into your switch, and then for example n===Number.MAX_VALUE in the case.

That case will evaluate to true or false, and then compare n to true or false. Is that your intent?

In the given solution, the switch is true, and then each comparison returnsa true or false…Which compares to true. It’s a shortcut, and not really recommended.

Got it :slight_smile: Thanks

What should I use instead of “true”?
How can I improve this code ?

If you aren’t matching one variable against multiple possible values, then don’t use a switch. In this case, you might want a if-else.


This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.