Js switch by 2 variables always execute first case - javascript

I have 2 variables : var1 and var2.
I found this answer https://stackoverflow.com/a/9235320/3917754 I try to implement it in my case :
switch (var1 | var2) {
case ('Contact' | true):
$('#btnCopyCompanyAddress').removeClass('hidden');
$('#btnCopyPersonalAddress').addClass('hidden');
break;
case ('Company' | true):
$('#btnCopyCompanyAddress').addClass('hidden');
$('#btnCopyPersonalAddress').removeClass('hidden');
break;
default:
$('#btnCopyCompanyAddress, #btnCopyPersonalAddress').addClass('hidden');
}
but always first case is executed even if var1 = Company and var2 = true.

It will always match the first case since 'any string string' | true === 1 results always 1.
Bitwise operators treated both value as string so parsing string result NaNor 0 and true result 1. The result would be calculates as NaN | 1, which results 1.(If the value is NaN or Infinity, it's converted to 0)
Refer : Bitwise operations on non numbers
So that would not work in this case, instead try concatenation.
switch (var1 + var2) {
case ('Contacttrue'):
$('#btnCopyCompanyAddress').removeClass('hidden');
$('#btnCopyPersonalAddress').addClass('hidden');
break;
case ('Companytrue'):
$('#btnCopyCompanyAddress').addClass('hidden');
$('#btnCopyPersonalAddress').removeClass('hidden');
break;
default:
$('#btnCopyCompanyAddress, #btnCopyPersonalAddress').addClass('hidden');
}

You can use "+" instead of "|" :
function Check(var1, var2) {
switch (var1 + var2) {
case ('Contact' + var2):
alert('1');
break;
case ('Company' + var2):
alert('2');
break;
default:
alert('0');
}
}

Related

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)

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.

Multiple variables with a switch (Javascript) [duplicate]

I am a newbie when it comes to JavaScript and it was my understanding that using one SWITCH/CASE statements is faster than a whole bunch of IF statements.
However, I want to use a SWITCH/CASE statement with two variables.
My web app has two sliders, each of which have five states. I want the behavior to be based on the states of these two variables. Obviously that is a whole heck of a lot of IF/THEN statements.
One way I thought about doing it was concatenating the two variables into one and then I could SWITCH/CASE that.
Is there a better way of accomplishing a SWITCH/CASE using two variables ?
Thanks !
Yes you can also do:
switch (true) {
case (var1 === true && var2 === true) :
//do something
break;
case (var1 === false && var2 === false) :
//do something
break;
default:
}
This will always execute the switch, pretty much just like if/else but looks cleaner. Just continue checking your variables in the case expressions.
How about a bitwise operator? Instead of strings, you're dealing with "enums", which looks more "elegant."
// Declare slider's state "enum"
var SliderOne = {
A: 1,
B: 2,
C: 4,
D: 8,
E: 16
};
var SliderTwo = {
A: 32,
B: 64,
C: 128,
D: 256,
E: 512
};
// Set state
var s1 = SliderOne.A,
s2 = SliderTwo.B;
// Switch state
switch (s1 | s2) {
case SliderOne.A | SliderTwo.A :
case SliderOne.A | SliderTwo.C :
// Logic when State #1 is A, and State #2 is either A or C
break;
case SliderOne.B | SliderTwo.C :
// Logic when State #1 is B, and State #2 is C
break;
case SliderOne.E | SliderTwo.E :
default:
// Logic when State #1 is E, and State #2 is E or
// none of above match
break;
}
I however agree with others, 25 cases in a switch-case logic is not too pretty, and if-else might, in some cases, "look" better. Anyway.
var var1 = "something";
var var2 = "something_else";
switch(var1 + "|" + var2) {
case "something|something_else":
...
break;
case "something|...":
break;
case "...|...":
break;
}
If you have 5 possibilities for each one you will get 25 cases.
First, JavaScript's switch is no faster than if/else (and sometimes much slower).
Second, the only way to use switch with multiple variables is to combine them into one primitive (string, number, etc) value:
var stateA = "foo";
var stateB = "bar";
switch (stateA + "-" + stateB) {
case "foo-bar": ...
...
}
But, personally, I would rather see a set of if/else statements.
Edit: When all the values are integers, it appears that switch can out-perform if/else in Chrome. See the comments.
I don't believe a switch/case is any faster than a series of if/elseif's. They do the same thing, but if/elseif's you can check multiple variables. You cannot use a switch/case on more than one value.
If the action of each combination is static, you could build a two-dimensional array:
var data = [
[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20],
[21,22,23,24,25]
];
The numbers in above example can be anything, such as string, array, etc. Fetching the value is now a one-liner (assuming sliders have a value range of [0,5):
var info = data[firstSliderValue][secondSliderValue];
You could give each position on each slider a different binary value from 1 to 1000000000
and then work with the sum.
Yeah, But not in a normal way. You will have to use switch as closure.
ex:-
function test(input1, input2) {
switch (true) {
case input1 > input2:
console.log(input1 + " is larger than " + input2);
break;
case input1 < input2:
console.log(input2 + " is larger than " + input1);
default:
console.log(input1 + " is equal to " + input2);
}
}
I did it like this:
switch (valueA && valueB) {
case true && false:
console.log(‘valueA is true, valueB is false’)
break;
case ( true || false ) && true:
console.log(‘valueA is either true or false and valueB is true’)
break;
default:
void 0;
}

Javascript - switch is for strings only?

Im not sure if I can use switch only for strings or that I can use it for numbers, booleans or events.
switch() can be used to compare any types: strings, objects, numbers.
The important thing to notice that switch() uses strict type comparison: ===.
For example:
Comparing strings
var a = '1';
switch (a) {
case 1:
console.log(1); // '1' === 1 returns false, no match
break;
default:
console.log('No match'); // will print 'No match'
}
Comparing objects
var a = 1;
switch (a.constructor) {
case Number:
console.log('number'); // prints 'number'
break;
case String:
console.log('string');
break;
default:
console.log('no match');
}
Im not sure if I can use switch only for strings
Nope, it should just be a valid expression as per the spec
See this demo,
this code alerts right
var a =1;
var b = 2;
switch(a+b)
{
case 1:
alert("wrong");
break;
case 2:
alert("wrong");
break;
case 3:
alert("right");
break;
default:
alert("wrong");
break;
}

Numeric comparison failure in a switch statement

"original post" : This function should compare the value of 'a' with several other values, but always defaults. My test shows that the value of 'a' or 'b' is never changed. Do I have the case a > statement incorrect or elsewhere?
Now I understand that I can not use comparison in the case statement:
Should I use a bunch of if statements and a while (a <> = 0) to do the multiple checking and decrementing?
The snippit below shows 'a' with a particular value. In the full function, actually 'a' gets a value from a random number in another function. It must be checked against 16 possible values and decremented, then rechecked until it finally reaches 0. The comparison values are actually powers of 2 (1 through 16).
function solution() {
var a = 18000;
var b = 0;
switch (a) {
case a > 30000:
a = a - 30000;
b = b++;
break;
case a > 16000:
b = b++; a = a - 16000;
break;
case a > 8000:
b = b++; a = a - 8000;
break;
default:
c = "defaulted!, Why?";
break;
}
window.alert (a + " " + b + " " + c);
}
Don't use switch for range checks like this. It's possible with
switch (true) {
case (a > 30000):
a = a - 30000;
b = b++;
but just don't do that.
Use if/else instead. While switch is really just an abstract if/else construct, use it for things like this:
switch(a){
case 1: ...
}
In a nutshell, you can't use boolean expressions in switch case labels. You'll need to rewrite the code as a series of if statements.

Categories