[javascript] Switch case with conditions

Am I writing the correct switch case?

var cnt = $("#div1 p").length;
                alert(cnt);
                switch (cnt) {
                    case (cnt >= 10 && cnt <= 20):
                        alert('10');
                        break;
                    case (cnt >= 21 && cnt <= 30):
                       alert('21');
                        break;
                    case (cnt >= 31 && cnt <= 40):
               alert('31');
                        break;
                    default:
                        alert('>41');
                }

For some reason, the alert does not occur when the conditions are matched!

This question is related to javascript jquery switch-statement

The answer is


A switch works by comparing what is in switch() to every case.

switch (cnt) {
    case 1: ....
    case 2: ....
    case 3: ....
}

works like:

if (cnt == 1) ...
if (cnt == 2) ...
if (cnt == 3) ...

Therefore, you can't have any logic in the case statements.

switch (cnt) {
    case (cnt >= 10 && cnt <= 20): ...
}

works like

if (cnt == (cnt >= 10 && cnt <= 20)) ...

and that's just nonsense. :)

Use if () { } else if () { } else { } instead.


function date_conversion(start_date){
    var formattedDate = new Date(start_date);
    var d = formattedDate.getDate();
    var m =  formattedDate.getMonth();
    var month;
    m += 1;  // JavaScript months are 0-11
    switch (m) {
        case 1: {
            month="Jan";
            break;
        }
        case 2: {
            month="Feb";
            break;
        }
        case 3: {
            month="Mar";
            break;
        }
        case 4: {
            month="Apr";
            break;
        }
        case 5: {
            month="May";
            break;
        }
        case 6: {
            month="Jun";
            break;
        }
        case 7: {
            month="Jul";
            break;
        }
        case 8: {
            month="Aug";
            break;
        }
        case 9: {
            month="Sep";
            break;
        }
        case 10: {
            month="Oct";
            break;
        }
        case 11: {
            month="Nov";
            break;
        }
        case 12: {
            month="Dec";
            break;
        }
    }
    var y = formattedDate.getFullYear();
    var now_date=d + "-" + month + "-" + y;
    return now_date;
}

What you are doing is to look for (0) or (1) results.

(cnt >= 10 && cnt <= 20) returns either true or false.

--edit-- you can't use case with boolean (logic) experessions. The statement cnt >= 10 returns zero for false or one for true. Hence, it will we case(1) or case(0) which will never match to the length. --edit--


This should work with this :

var cnt = $("#div1 p").length;

            switch (true) {
                case (cnt >= 10 && cnt <= 20):
                    alert('10');
                    break;
                case (cnt >= 21 && cnt <= 30):
                   alert('21');
                    break;
                case (cnt >= 31 && cnt <= 40):
                    break;
                default:
                    alert('>41');
            }

Switch case is every help full instead of if else statement :

     switch ($("[id*=btnSave]").val()) {
        case 'Search':
            saveFlight();
            break;
        case 'Update':
            break;
        case 'Delete':
            break;
        default:
            break;
    }

Something I came upon while trying to work a spinner was to allow for flexibility within the script without the use of a ton of if statements.

Since this is a simpler solution than iterating through an array to check for a single instance of a class present it keeps the script cleaner. Any suggestions for cleaning the code further are welcome.

$('.next').click(function(){
        var imageToSlide = $('#imageSprite'); // Get id of image

        switch(true) {
            case (imageToSlide.hasClass('pos1')):
                imageToSlide.removeClass('pos1').addClass('pos2');
                break;
            case (imageToSlide.hasClass('pos2')):
                imageToSlide.removeClass('pos2').addClass('pos3');
                break;
            case (imageToSlide.hasClass('pos3')):
                imageToSlide.removeClass('pos3').addClass('pos4');
                break;
            case (imageToSlide.hasClass('pos4')):
                imageToSlide.removeClass('pos4').addClass('pos1');
        }
    }); ` 

Ok it is late but in case you or someone else still want to you use a switch or simply have a better understanding of how the switch statement works.

What was wrong is that your switch expression should match in strict comparison one of your case expression. If there is no match it will look for a default. You can still use your expression in your case with the && operator that makes Short-circuit evaluation.

Ok you already know all that. For matching the strict comparison you should add at the end of all your case expression && cnt.

Like follow:

switch(mySwitchExpression)
case customEpression && mySwitchExpression: StatementList
.
.
.
default:StatementList

_x000D_
_x000D_
var cnt = $("#div1 p").length;
alert(cnt);
switch (cnt) {
case (cnt >= 10 && cnt <= 20 && cnt):
    alert('10');
    break;
case (cnt >= 21 && cnt <= 30 && cnt):
    alert('21');
    break;
case (cnt >= 31 && cnt <= 40 && cnt):
    alert('31');
    break;
default:
    alert('>41');
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
<p> p1</p>
<p> p2</p>
<p> p3</p>
<p> p3</p>
<p> p4</p>
<p> p5</p>
<p> p6</p>
<p> p7</p>
<p> p8</p>
<p> p9</p>
<p> p10</p>
<p> p11</p>
<p> p12</p>
</div>
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to switch-statement

Switch in Laravel 5 - Blade Switch case: can I use a range instead of a one number SQL use CASE statement in WHERE IN clause SSRS Conditional Formatting Switch or IIF Switch statement equivalent in Windows batch file OR operator in switch-case? Regarding Java switch statements - using return and omitting breaks in each case Using two values for one switch case statement C# how to use enum with switch Switch statement multiple cases in JavaScript