jquery Using ranges in switch cases? - javascript

Switch cases are usually like
Monday:
Tuesday:
Wednesday:
etc.
I would like to use ranges.
from 1-12:
from 13-19:
from 20-21:
from 22-30:
Is it possible? I'm using javascript/jquery by the way.

you could try abusing the switch fall through behaviour
var x = 5;
switch (x) {
case 1: case 2: case 3: case 4: ...
break;
case 13: case 14: case 15: ...
break;
...
}
which is very verbose
or you could try this
function checkRange(x, n, m) {
if (x >= n && x <= m) { return x; }
else { return !x; }
}
var x = 5;
switch (x) {
case checkRange(x, 1, 12):
//do something
break;
case checkRange(x, 13, 19):
...
}
this gets you the behaviour you would like. The reason i return !x in the else of checkRange is to prevent the problem of when you pass undefined into the switch statement. if your function returns undefined (as jdk's example does) and you pass undefined into the switch, then the first case will be executed. !x is guaranteed to not equal x under any test of equality, which is how the switch statement chooses which case to execute.

Late to the party, but upon searching for an answer to the same question, I came across this thread. Currently I actually use a switch, but a different way. For example:
switch(true) {
case (x >= 1 && x <= 12):
//do some stuff
break;
case (x >= 13 && x <= 19):
//do some other stuff
break;
default:
//do default stuff
break;
}
I find this a lot easier to read than a bunch of IF statements.

You can make interesting kludges. For example, to test a number against a range using a JavaScript switch, a custom function can be written. Basically have the function test a give n value and return it if it's in range. Otherwise returned undefined or some other dummy value.
<script>
// Custom Checking Function..
function inRangeInclusive(start, end, value) {
if (value <= end && value >= start)
return value; // return given value
return undefined;
}
// CODE TO TEST FUNCTION
var num = 3;
switch(num) {
case undefined:
//do something with this 'special' value returned by the inRangeInclusive(..) fn
break;
case inRangeInclusive(1, 10, num):
alert('in range');
break;
default:
alert('not in range');
break;
}
</script>
This works in Google Chrome. I didn't test other browsers.

Nope, you need to use an if/else if series to do this. JavaScript isn't this fancy. (Not many languages are.)

Related

DIfferent between break and return in swith loop JS ? And what using in my logic ( looking code ) [duplicate]

This question already has answers here:
Difference between Return and Break statements
(14 answers)
Closed 2 years ago.
And i don't know is this good solution to using return or to use break?
switch (arg.seriesName) {
case 'Test':
return 'Test'
case 'One':
return 'One'
case 'two':
return 'two'
default:
break;
}
break will allow you the function to continue processing, whereas return will end the function. Returning out of the switch is fine if that's all you want to do in the function.
E.g.
Return
function foo(x) {
switch(x) {
case 'y':
return;
}
// This will never run if x === 'y'
}
Break
function foo(x) {
switch(x) {
case 'y':
break;
}
// This will still run if x === 'y'
}
Just to clarify, that one is a switch statement, not a loop.
Anyway, break is used to stop fall-through: that is, when one of the cases match, it prevents the other from matching as well.
The difference between return and break depends on your context: if you're inside a function, return will stop the execution of the function altogether, whereas break will make the switch statement only match one case and then go on with the execution.
A case clause used to match against expression. If the expression matches the specified valueN, the statements inside the case clause are executed until either the end of the switch statement or a break.
The break stops to execution the other cases.
In your example you return inside the case so it will left the function and return the value so there is no need for the break;
Here with the breaks in each case prints only the case which is hitting
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 are out of ${expr}.`);
}
But if you forget the break it also prints out the cases after the hitting one
const expr = 'Papayas';
switch (expr) {
case 'Oranges':
console.log('Oranges are $0.59 a pound.');
case 'Mangoes':
case 'Papayas':
console.log('Mangoes and papayas are $2.79 a pound.');
// expected output: "Mangoes and papayas are $2.79 a pound."
default:
console.log(`Sorry, we are out of ${expr}.`);
}

why does this simple switch statement always run the default

Ok guys, It seems like this switch statement is forever doomed to NOT work.
The initial idea was to create a variable x which is a prompt, the user will have to select enter any number and that would be the value of x.
Then under the first case of the switch, if x is less than 0.5 then it will simply console.log "less".
If x is more than 0.5 it will simply console.log "more".
If for some reason the program didn't work as expected the default is to console.log "this is the default"
Then i added a console.log of x in the end just to know what number did the user enter.
Lets try it!
I tried and tried and regardless of what number i enter it always printed "this is the default". Then printed the value of x.
I ended up going Rambo and removing the prompt and declaring x to be 0.6. It ought to print "more" but it still doesn't.
var x = 0.6;
switch (x) {
case x < 0.5:
console.log("less");
break;
case x > 0.5:
console.log("more");
break;
default:
console.log("its the dflt");
};
console.log(x);
So I'm wondering whats wrong with this code. Help
switch compares what you switch with against the cases. So, if you have case x < 0.5: which you want to run, that case will run if the expression you switched against was true:
var x = 0.6;
switch (true) {
case x < 0.5:
console.log("less");
break;
case x > 0.5:
console.log("more");
break;
default:
console.log("its the dflt");
};
console.log(x);
If you switch against x itself, a case will only run if the case evaluates to the same value as x, which, here, is 0.6, eg:
var x = 0.6;
switch (x) {
case 0.6:
console.log('x is exactly 0.6');
break;
default:
console.log("x is something other than 0.6");
};
console.log(x);
But that's not flexible at all, and isn't what you want.
Personally, I'd prefer if/else, it's a lot easier to read (and, as some points out in comments, is a lot faster):
var x = 0.6;
if (x < 0.5) {
console.log("less");
} else if (x > 0.5) {
console.log("more");
} else {
console.log('neither less nor more; equal or NaN');
}
Switch compares the value of x to the value of the cases. In your code x < 0.5 evaluates to true. Instead of going to that case like if-statements, the switch case compares x and true. Since x is a number, x will never equal true so the default case is always taken.
I would use if-statements instead of a switch in this instance. Switches are better for enumerations (checking if x is a specific value out of a set of values, not a range of values)
CertainPerformance has answered you question very well however if you still don't understand how to use switch I would recommend you use "if statements" until you have the time to read more on using switch.
var x = 0.6;
if (x < 0.5) {
console.log("less");
}
else if (x > 0.5) {
console.log("more");
}
else {
console.log("its the dflt");
}
console.log(x);
Hope this is easier for you :)

How to correctly write a condition in switch? [duplicate]

This question already has answers here:
javascript switch(true)
(5 answers)
Closed 5 years ago.
Good afternoon!
Why does the first option work - switch (true), and the second option does not work - switch (a)?
First:
var a= prompt('Enter value', '');
switch(true)
{
case a>10:
alert('a>10');
break;
case a<10:
alert('a<10');
break;
default:
alert('a===10');
Second:
var a= prompt('Enter value', '');
switch(a)
{
case a>10:
alert('a>10');
break;
case a<10:
alert('a<10');
break;
default:
alert('a===10');
Why does the first option work - switch (true), and the second option
does not work - switch (a)?
As per documentation
The switch statement evaluates an expression, matching the
expression's value to a case clause, and executes statements
associated with that case.
So, in your first option true will match to either a < 10 or a > 10, however in second option, a being a string may not match to either of them.
Edit: I just realize OP ask for the difference instead of why it won't work, sorry for misunderstanding the question
It should work nicely
var a = prompt('Enter value', '');
switch (true) {
case (a > 10):
alert("a > 10");
break;
case (a < 10):
alert("a < 10");
break;
default:
alert('a == 10');
}
It's because a > 10 is true, like the switch(true), while switch(a) was passed a, which is not true. Of course, you should cast a. a = +a or use parseInt() or parseFloat().
Here's what you probably meant to do:
var a = prompt('Enter value');
if(+a > 10){
alert('a > 10');
}
else if(a !== '' && +a < 10){
alert('a < 10');
}
else if(+a === 10){
alert('a === 10');
}
else{
alert('Really, you should avoid using prompt and alert!');
}
// notice this is less code than that pointless switch
You need to convert the user input from a string to an integer, like so
a = parseInt(a)

How to use switch to compare values between values

I'm learning JavaScript with a very basic and simple Level Upper system by a button using a XP Table to set var named Level a value and print it.
How can I use the switch statement to compare numbers between 10 and 20 as example, and return a var named Level the value of 2(Lv. 2)?
I've tried using "case 10...20" (3 dots as in another languages) but it didn't work!
I tried to use if statement, but it doesn't work properly. :/
var Exp = 1;
var Level = 1;
function MaisExp()
{
Exp++;
document.getElementById("console").innerHTML = "+1 XP! | "+" Total: "+Exp+" xp points";
VerLevel();
}
function VerLevel()
{
switch(Exp)
{
case 0...10: ***< --- dots didn't work.***
{
Level=1;
}
case 20:
{
Level=2;
}
case 40:
{
Level=1;
}
case 80:
{
Level=1;
}
}
document.getElementById("tela").innerHTML = Level;
}
You can use if statements like this:
if(Exp >= 0 && Exp <= 10)
{
}
else if(Exp <= 20)
{
}
else if(Exp <= 30) etc...
The case statement doesn't work with multiple validations, it can only handle one per case. However, you can list multiple cases, for example:
switch(age){
case 0:// If age is 0, it would enter here, since there is no "break;" it goes down to 1
case 1:// Same as above
case 2:// Same as above
case 3:// Since this one has a break, this code is executed and then the switch terminates
console.log('This toy is not right for this person');
break;
default:// This special case fires if age doesn't match any of the other cases, or none of the other cases broke the flow
console.log('This toy is good for this person');
}
So, in your code, it should be something like:
switch(Exp)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
Level=1;
break;
case 20:
Level=2;
break;
case 40:
Level=1;
break;
case 80:
Level=1;
break;
}
But, since you want all to be level 1, but 20, you could also use the default case, like this:
switch(Exp)
{
case 20:
Level=2;
break;
default:
Level=1;
}
While you have already a default value of 1, you could take it in the function and check onle the condition for level = 2.
function VerLevel() {
Level = 1;
if (Exp === 20) {
Level = 2;
}
document.getElementById("tela").innerHTML = Level;
}
I suggest to change the style of variable and function to start with lower case letters, because functions with upper case letters denotes instanciable/constructor functions, which can be uses with new operator.

Why Switch statement only working with true keyword?

Can anyone explain to me why first one is not working and second one is working?
First Statement
function test(n) {
switch (n) {
case (n == 0 || n == 1):
console.log("Number is either 0 or 1");
break;
case (n >= 2):
console.log("Number is greater than 1")
break;
default:
console.log("Default");
}
}
Second Statement
function test(n) {
switch (true) {
case (n == 0 || n == 1):
console.log("Number is either 0 or 1");
break;
case (n >= 2):
console.log("Number is greater than 1")
break;
default:
console.log("Default");
}
}
The parameter which is given to the switch will be compared using ===. In cases which you have, you have expressions which result to boolean type: n==0 || n==1 or n >= 2. When you pass a number , it tries to compare your number with a result given from the expression in cases. So for example with the given number 1 it tries to compare 1 === (1 == 0 || 1 == 1) -> 1 === true which returns false (strict comparison). So you get the Default text every time.
For the first case, you need to have numbers in the cases of your switch , not a boolean (n==0 || n==1 results to boolean).
With the second case, you have in the switch value true of type boolean.When you pass again 1 the comparing goes like true === (1 == 0 || 1 == 1) -> true === true and it returns true. So you get the desired result according to your value n. But the second case has no goals with using true as the value. You can replace it with a if else if statement.
If you want to get the same result for many cases you need to write 2 cases above each other. See this
case 0:
case 1:
result
Here the cases have type number, not boolean.
Code example.
function test(n){
switch (n) {
case 0:
case 1:
console.log("Number is either 0 or 1");
break;
case 2:
console.log("Number is 2")
break;
default:
console.log("Default");}
}
test(0);
test(1);
test(2)
switch is shorthand for a bunch of ifs.
switch(n) {
case x:
a();
break;
case y:
b();
break;
}
... is equivalent to:
if(n == x) {
a();
} else if(n == y) {
b();
}
So your first piece of code:
switch (n) {
case (n==0 || n==1):
console.log("Number is either 0 or 1");
break;
case (n>=2):
console.log("Number is greater than 1")
break;
default:
console.log("Default");}
}
... is equivalent to:
if(n == (n==0 || n==1)) {
console.log("Number is either 0 or 1");
} else if ( n == ( n >= 2)) {
console.log("Number is greater than 1");
} else {
console.log("Default");
}
I hope you can see that n == (n==0 || n==1) and n == ( n >= 2) are both nonsense. If n is 0, for example, the first will evaluate to 0 == true. In many languages this will cause a compiler error (comparing different types). I don't especially want to think about what it does in Javascript!
Your second example:
switch (true) {
case (n==0 || n==1):
console.log("Number is either 0 or 1");
break;
case (n>=2):
console.log("Number is greater than 1")
break;
default:
console.log("Default");
}
Is equivalent to:
if(true == (n==0 || n==1)) {
console.log("Number is either 0 or 1");
} else if(true == (n>=2)) {
console.log("Number is greater than 1");
} else {
console.log("Default");
}
... in which at least the condition statements true == (n==0 || n==1) and true == (n >=2) make sense.
But this is an unconventional way to use switch in most languages. The normal form is to use the value you're testing as the parameter to switch and for each case to be a possible value for it:
switch(n) {
case 0:
case 1:
console.log("n is 0 or 1");
break;
case 2:
console.log("n is 2);
break;
default:
console.log("n is some other value");
}
However switch doesn't provide a cleverer case than a full equality check. So there's no case >2 && <5.
Your can either use your trick using switch(true) (in Javascript -- there are many languages in which this won't work), or use if/else.
switch uses strict comparison.
You take a number in the switch statement and in cases, just comparsions which return a boolean value.
A switch statement first evaluates its expression. It then looks for the first case clause whose expression evaluates to the same value as the result of the input expression (using strict comparison, ===) and transfers control to that clause, executing the associated statements. (If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.) If no matching case clause is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements. If no default clause is found, the program continues execution at the statement following the end of switch. By convention, the default clause is the last clause, but it does not need to be so.

Categories