JavaScript: using a condition in switch case
This works:
switch (true) {
case liCount == 0:
setLayoutState('start');
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
case liCount<=5 && liCount>0:
setLayoutState('upload1Row');
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
case liCount<=10 && liCount>5:
setLayoutState('upload2Rows');
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
case liCount>10:
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
}
The only thing necessary is switch(true){...}
and for your case expressions to evaluate to booleans.
It works because, the value we give to the switch is used as the basis to compare against. Consequently, the case expressions, also evaluating to booleans will determine which case is run. Could also turn this around, and pass switch(false){..}
and have the desired expressions evaluate to false instead of true.. but personally prefer dealing with conditions that evaluate to truthyness. However, it does work too, so worth keeping in mind to understand what it is doing.
Eg: if liCount is 3, the first comparison is true === (liCount == 0)
, meaning the first case is false. The switch then moves on to the next case true === (liCount<=5 && liCount>0)
. This expression evaluates to true, meaning this case is run, and terminates at the break
. I've added parentheses here to make it clearer, but they are optional, depending on the complexity of your expression.
It's pretty simple, and a neat way (if it fits with what you are trying to do) of handling a long series of conditions, where perhaps a long series of ìf() ... else if() ... else if () ...
might introduce a lot of visual noise or fragility.
Use with caution, because it is a non-standard pattern, despite being valid code.
JavaScript conditional switch statement
In a switch
statement, the evaluated value of the switch
expression is compared the the evaluated values of the cases. So here the value of raw_value
(number) is compared to raw_value > 10.0
(comparison expression) and raw_value > 5.0
(comparison expression).
So unless one of your case expressions yield a number equal to 11.0
or you use the switch
expression true
, you will always get the default case.
Just use a simple if
/else
instead:
var raw_value = 11.0;
if (raw_value > 10.0) {
height = 48;
width = 36;
} else if (raw_value > 5.0) {
height = 40;
width = 30;
} else {
height = 16;
width = 12;
}
Switch case with conditions
You should not use switch
for this scenario. This is the proper approach:
var cnt = $("#div1 p").length;
alert(cnt);
if (cnt >= 10 && cnt <= 20)
{
alert('10');
}
else if (cnt >= 21 && cnt <= 30)
{
alert('21');
}
else if (cnt >= 31 && cnt <= 40)
{
alert('31');
}
else
{
alert('>41');
}
JavaScript switch-case using a condition
The switch statement does compare its argument with the values of the expressions in the cases.
In your code, it does compare the number
with those boolean results from the cases, so it only gets in the first case when your number
is 1 (because 1 == true
) and falls to the default
otherwise. You could simply compare them to true
, like
switch (true) {
case number >= 1 && number <= 9:
alert("The number " + number + " is a single digit number.");
break;
case number >= 10 && number <= 99:
alert("The number " + number + " is a two digit number.");
break;
case number >= 100 && number <= 999:
alert("The number " + number + " is a three digit number.");
break;
case number >= 1000 && number <= 9999:
alert("The number " + number + " is a four digit number.");
break;
default:
alert("Your number has 5 or more digits.");
}
but it would be cleaner to use an if-else
construct:
if (number >= 1 && number <= 9)
alert("The number " + number + " is a single digit number.");
else if (number >= 10 && number <= 99)
alert("The number " + number + " is a two digit number.");
else if (number >= 100 && number <= 999)
alert("The number " + number + " is a three digit number.");
else if (number >= 1000 && number <= 9999)
alert("The number " + number + " is a four digit number.");
else
alert("Your number has 5 or more digits.");
Btw, much shorter would be
var l = String(number).length;
alert(l<5
? "The number "+number+" is a "+[,"single","two","three","four"][number]+" digit number."
: "Your number has 5 or more digits."
);
JavaScript Switch Statement - Condition in Case
You can use a fall-through:
switch (expression) {
case "exp1":
case "exp2":
// code block
break;
default:
// default code block
}
how switch in javascript works when it satisfy all cases condition
A switch statement executes the block for the first case
that it matches (as per the order the case statements are listed top to bottom).
If that case
contains a break
, then no other case
statements are matched as execution will resume after the switch
block.
Case in Switch statement involving array with conditions
function showFiletRelateddata(selectedFilter) { var filt = selectedFilter; var supp = "" for (var i = 0; i < filt.length; i++) { //loop over length of array supp = supp + filt[i]; // concat elements of array } switch (supp) { case "RequestReservation": // if case contains one of the condition case "ReservationRequest": console.log("RequestReservation"); break; case "Request": console.log("Request"); break; case "Reservation": console.log("Reservation"); break; default: console.log("No data"); } }var a = ["Reservation", "Request"];var b = ["Request","Reservation"];var c = ["Reservation"];var d = ["Request"]; showFiletRelateddata(a); showFiletRelateddata(b); showFiletRelateddata(c); showFiletRelateddata(d);
Expression inside switch case statement
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 if
–else
statement would probably be more concise, and you’d not have to worry about accidental fall-through. But there it is anyway.
Related Topics
Keyword 'Const' Does Not Make the Value Immutable. What Does It Mean
How to Include Js File in Another Js File
What Advantages Does Using (Function(Window, Document, Undefined) { ... })(Window, Document) Confer
How to Force Angular2 to Post Using X-Www-Form-Urlencoded
Image Preloader JavaScript That Supports Events
Adding a New Array Element to a JSON Object
How to Debug Jquery Ajax Calls
How to Resize Twitter Bootstrap Modal Dynamically Based on the Content
<Script> Tag VS <Script Type = 'Text/Javascript'> Tag
Keys in JavaScript Objects Can Only Be Strings
Cryptic "Script Error." Reported in JavaScript in Chrome and Firefox
How to Extend a Class Without Having to Use Super in Es6
Javascript/Jquery: Test If Window Has Focus