Using || in javascript switches - javascript

Is this code possible?
switch (rule)
{
case 'email' || 'valid_email':
valid = this.validate_email(field);
break;
}

No, it is not possible, Switch statements doesn't do arithmetic calculus.
However, you can use case chaining or a bunch of if's:
switch (rule)
{
case 'email':
case 'valid_email':
valid = this.validate_email(field);
break;
}

Close, but this will work:
switch (rule)
{
case 'email':
case 'valid_email':
valid = this.validate_email(field);
break;
}
The reason why it works is that without a break;, execution continues within the switch block.

Related

Are there any possibilities to use "goto" inside switch statement in javascript?

This is my example program in JS. I have to iterate or loop inside the switch statement. So I have used goto, but it doesn't working.
Are there any other options to loop this or is my syntax wrong?
var input = 1;
switch (input)
{
case 1:
...
break;
case 2:
...
break;
case 3:
...
if (..) { }
else
{
goto case 2;
}
break;
default:
alert("No Return");
break;
}
Are there any possibilities to use "goto" inside switch statement in javascript?
No, there are no possibilities to use "goto" inside switch statement, or anywhere else, since JavaScript has no such statement.
To solve your problem, as suggested in a comment, organize your cases (moving 3 above 2) so you can use fall-through:
var input = 1;
switch (input)
{
case 1:
...
break;
case 3:
...
if (..) { ...; break; }
// fall through to case 2
case 2:
...
break;
default:
alert("No Return");
break;
}
In this case, make sure to comment the fall-through so people looking at your code don't think it's a bug. You may also need to add a hint so that your linter does not complain.
Or, just put the logic common to 2 and 3 in a little function:
function someLogicFor2Or3() { ... }
case 2:
someLogicFor2OrMaybe3();
break;
case 3:
...
if (..) { }
else someLogicFor2OrMaybe3();
break;
I have used the following technique to do this :
var input = 1;
while (1) {
switch (input) {
case 1:
...
break; // switch
case 2:
...
break; // switch
case 3:
...
if (..) { }
else {
input = 2; // goto case 2;
continue; // while
}
break; // switch
default:
alert ("No Return");
break; // switch
}
break; // while
}

Cannot read property 'done' of undefined due to switch

I have a function which gaining data by ajax. The problem is that construction switch causing this error:
cannot read property 'done' of undefined
I don't know why...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
function changeSelect(input,type)
{
var out;
switch(type)
{
case "sport" : out=$.post("/ajax/ajax.php",{sport:input.value});
case "competition" :out=$.post("/ajax/ajax.php",{competition.value});
}
out.done(function(data)
{
$("#output").html(data);
});
}</script>
Thanks for answer.
The likely cause of the error you are getting is that the value of type does not match either of your case statements. Thus, out remains undefined and gives you the error you see.
In addition, you must use break; statements in case of your case: statements and {competition.value} is not valid ES5 Javascript. Perhaps you want something like this:
function changeSelect(input, type) {
var out;
switch (type) {
case "sport":
out = $.post("/ajax/ajax.php", {sport: input.value});
break;
case "competition":
out = $.post("/ajax/ajax.php", {sport: competition.value});
break;
default:
break;
}
if (out) {
out.done(function(data) {
$("#output").html(data);
});
}
}
I don't know exactly what you meant with your {competition.value}. I guessed that maybe you wanted it to be {sport: competition.value}, but I don't see competition defined anywhere so I'm not really sure.
Or, perhaps remove some duplicate code and use this:
function changeSelect(input, type) {
var val;
switch (type) {
case "sport":
val = input.value;
break;
case "competition":
val = competition.value;
break;
default:
break;
}
if (val) {
$.post("/ajax/ajax.php", {sport: val}).then(function(data) {
$("#output").html(data);
});
}
}

A switch statement doesn't work when the equivalent if statement does

switch(type)
{
case 'home':
console.log('home switch');
break;
}
The above code does not write out to the console, neither does the following:
switch(type)
{
case "home":
console.log('home switch');
break;
}
The following, however, does:
if (type == 'home')
{
console.log('home if');
}
I don't have a clue why. This isn't a show-stopper, I can use the if statement instead, but I'm genuinely curious as to why this is the case.
NOTE: These statements are a straight replace, nothing else to consider here. No change in scope, no code I'm not mentioning that could be interfering with the value of type.
That's not the equivalent if-statement. The switch statement is specified to use the strict equality === operator.

javascript switch() or if()

which would be better if i do this:
if(message == 'redirect')
{
is_valid.accepted = true;
}
else if(message == 'invalid id')
{
is_valid.accepted = false;
}
else
{
is_valid.accepted = false;
}
or i do it this way
switch (message)
{
case 'invalid id':
default:
is_valid.accepted = false;
break;
case 'redirect':
is_valid.accepted = true;
break;
}
You might use switch if you foresaw needing to add lots of new cases.
If you won't be adding many new cases, I might do, for clarity:
is_valid.accepted = message=='redirect';
(also note that your check for 'invalid id' does nothing)
Nevertheless if you had to add new things, notice how it's good you don't have to repeat yourself don't have to repeat yourself don't have to repeat yourself, also the sexy formatting:
switch (message)
{
case 'invalid id':
case 'penguin invasion':
case 'the internet is down':
case 'error not enough caffeine':
is_valid.accepted = false;
break;
case 'redirect':
case 'upvote me':
case 'vip':
case 'flamewar':
is_valid.accepted = true;
break;
default:
is_valid.accepted = false;
// perhaps log or something
}
Imagine all those ugly else and else-ifs you'd have otherwise.
sidenote:
If you had really complicated rules, but still a whitelist-blacklist-on-a-single-flag paradigm, then:
var blacklist = ['invalid id', 'penguin invasion', 'the internet is down' 'error not enough caffeine'];
var whitelist = ['redirect', 'upvote me', 'vip', 'flamewar'];
is_valid.accepted = whitelist.indexOf(message)!=-1;
You might also do this if you wanted to dynamically construct your whitelist.
It depends on your definition of better. Do you want it to be a better reading experience or better performance?
I always jsPerf things. I don't really care much about readability if it makes my code faster/proper.
Here is a jsPerf of a bunch of different switch vs. if/else if/if ==/if === statements.
http://jsperf.com/switch-if-else/16
This is revision 16 of the test. So if you are looking at this 10 weeks from now make sure you scroll to the bottom and grab the most recent test.
The switch statement is more efficient/expressive than if/else in some cases. While the following if/else statement
let x = 123;
if (x) {/*...*/} // implicit type casting (to boolean)
else {/*...*/}
can be easily converted to:
switch (!!x) { // explicit type casting (to boolean)
case true: /*...*/ break;
default: /*...*/
}
this switch statement on the other hand
function algo(x) {/*...performing a complex algorithm...*/}
switch (algo(123)) { // executed once
case "result 1": /*...*/ break;
case "result 2": /*...*/ break;
case "result 3": /*...*/ break;
default: /*...*/
}
results in an incredible inefficient if/else statement (switch is more efficient):
if (algo(123) === "result 1") {/*...*/}
else if (algo(123) === "result 2") {/*...*/}
else if (algo(123) === "result 3") {/*...*/}
else {/*...*/}
or requires an if/else with additional variable, which is declared for this purpose exclusively:
let y = algo(x); // additional variable
if (y === "result 1") {/*...*/}
else if (y === "result 2") {/*...*/}
else if (y === "result 3") {/*...*/}
else {/*...*/}
Please note that additional elements (like variables) cause more complexity and complexity makes programs more error prone. The switch statement doesn't need such a variable, because it is more expressive.
Switch is better if you're working with a long list of possible conditions on the same variable. In this case, I don't think there's much reason to use switch() unless you prefer the syntax.
If you go with the if statement, I personally prefer setting default values above the if, like this:
is_valid.accepted = false;
if(message == 'redirect')
{
is_valid.accepted = true;
}
That way, you always default to a safe behavior that is less likely to break if you add more options later on. Also, you see the default behavior at a glance without having to read through the if-then-else logic. And it's much shorter code.
Ternary?
is_valid.accepted = (message !== 'invalid id') ? true : false;

javascript switch(true)

Hi i am trying to handle an ajax json response
here is my code
success: function (j) {
switch(true)
{
case (j.choice1):
alert("choice2");
break;
case (j.choice2):
alert("choice2");
break;
default:
alert("default");
break;
}
}
based on what j is return i do my action BUT i keep getting the default.
I have alert the j values and come correct.Some how case (j.choice1) case (j.choice2) is not working.
I tried case (j.choice1!="") (j.choice2!="") But in this scenario i keep getting the first choice.
What am i missing
It works for me:
var a = 0, b = true;
switch(true) {
case a:
console.log('a');
break;
case b:
console.log('b');
break;
}
However, the case labels must be equal to true, not just implicitly true.
Also, only the first case that evaluates to true will execute.
SOLVED
Based on SLaks answer i modify the code as below
if(j.choice1){ var choice1=true;} else { var choice1=false;}
if(j.choice2){ var choice2=true;} else { var choice2=false;}
switch(true)
{
case choice1:
alert("choice1");
break;
case choice2:
alert("choice2");
break;
default:
alert("default");
break;
}
For all asking why switch and not if.
Switch will execute only 1 statement, but if can execute more than 1 if any mistake come form response (for example if set choice1 and choice 2 the if will alert both but switch will alert only choice1).
The response expecting as choice has to do with credit card charge to bank so i want to ensure that only 1 action will exetute
Thank to all
You need to read up on the switch statement. You should not be switching on a constant value.
It appears that you need to use if statements, as you don't really want to be switching on your j value:
success: function (j) {
if (j.choice1)
{
alert("choice1");
break;
}
if (j.choice2)
{
alert("choice2");
break;
}
alert("default");
}
}
In a case like this, a better way to do this is probably something like:
success: function (j) {
if(j.choice1 || j.choice2) {
alert("choice2");
} else {
alert("default");
}
}
Why not use an object literal instead of a switch(true) ?
const j= {
choice1: false,
choice2: true
};
const map = {
true: 'default',
...(j.choice1 ? {[`${j.choice1}`]: 'choice1'} :{}),
...(j.choice2 ? {[`${j.choice2}`]: 'choice2'} :{})
}['true']
console.log(map) // 'choice2'

Categories

Resources