I need to make a case execute at the last. Any ideas?
$.each(dataNames, function (varName, itemVal) {
switch (varName)
{
case "afshin":
alert('afshin');
break;
case "saeed":
alert('saeed');
break;
case "larry":
alert('larry');
break;
case "abc":
alert('abc');
break;
default:
alert('Default case');
break;
}
});
from the code above i need the case 'abc' to get executed at the last of all cases as i'm manipulating some code which has to execute from the other cases.
FYI, dataNames is a JSON object
Related
all. I'm fairly new to JavaScript - currently trying to understand the switch statement. I'm having a problem understanding how I still got a return value when I did no assignments to my result variable. The switch statement is nested in a function.
function caseInSwitch(val) {
let result = "";
switch(val) {
case 1:
return "alpha";
break;
case 2:
return "beta";
break;
case 3:
return "gamma";
break;
case 4:
return "delta";
break;
}
return result;
}
caseInSwitch(1);
I expect result to be an empty string "", but it shows the following value immediately... without any assignments...!
You're returning in the switch statement. In the case where val equals 1, the switch statement never gets past case 1. The function doesn't return result, it executes return "alpha".
That return statement terminates the function:
function caseInSwitch(val) {
console.log("1: function start. Val:", val);
let result = "";
console.log("2: before switch");
switch(val) {
case 1:
console.log("3: before return alpha");
return "alpha";
console.log("4: after return alpha");
break;
case 2:
return "beta";
break;
case 3:
return "gamma";
break;
case 4:
return "delta";
break;
}
console.log("5: after switch");
return result;
}
var finalResult = caseInSwitch(1);
console.log("Final result:", finalResult);
As you can see, only statements 1-3 get logged.
The return statement in the switch also means the breaks are redundant:
switch(val) {
case 1:
return "alpha";
case 2:
return "beta";
case 3:
return "gamma";
case 4:
return "delta";
}
Those break statements are only necessary to terminate the case, if you're not returning out of the case:
let variable = "";
switch(val) {
case 1:
variable = "alpha";
break;
case 2:
variable = "beta";
break;
case 3:
variable = "gamma";
break;
case 4:
variable = "delta";
break;
}
console.log(variable);
The answer is pretty simple, you are passing 1 as the value for val in caseInSwitch. In the switch block, 1 is matched with case 1 and the function returns alpha. Keep in mind the return in the switch block, makes the control return from the function itself and not just from the switch block
Is it possible to make like a two layer switch case? Say I have two expressions, that inside the the first case it looks for the second expression? I have googled but I have not found anything that I look for.
switch (Middle, Direction) {
case true:
case 'left':
code block
break;
case 'right':
code block
break;
break;
case false:
case 'left':
code block
break;
case 'right':
code block
break;
break;
default:
code block
}
Yes, you have to use individual, complete switches:
switch (Middle) {
case true:
switch (Direction) {
case 'left':
//code block
break;
case 'right':
//code block
break;
}
break;
case false:
switch (Direction) {
case 'left':
//code block
break;
case 'right':
//code block
break;
}
break;
default:
//code block
}
Note that in the above, if Direction isn't 'left' or 'right' but Middle is true or false (which, if it's really a boolean, it must be), then no default code is run as the subordinate switches don't have defaults.
Alternately, you might combine Middle and Direction, which makes it easier to use a default for non-matching cases:
switch (Middle+'|'+Direction) {
case 'true|left':
//code block
break;
case 'true|right':
//code block
break;
case 'false|left':
//code block
break;
case 'false|right':
//code block
break;
default:
//code block
}
Or look at a dispatch object:
var actions = {
"true|left": function() {
// code for Middle = true, Direction = left
},
"true|right": function() {
// code for Middle = true, Direction = right
},
"false|left": function() {
// code for Middle = false, Direction = left
},
"false|right": function() {
// code for Middle = false, Direction = right
},
"default": function() {
// code for the default
}
};
(actions[Middle+"|"+Direction] || actions.default)();
...though in this specific case it doesn't buy you much of anything over a switch.
Just use another switch in your case.
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
}
In javascript switch statements, I would like to execute some function if any one of the case is satisified:
switch (myVar){
case 0:
do_something_0();
break;
case 1:
do_something_1();
break;
// I want to execute myFunc() if myVar === 1 or myVar === 2
}
I came up with the idea of having auxiliary variable haveMatched, like this.
var haveMatched=false;
switch (myVar){
case 0:
do_something_0();
haveMatched=true;
break;
case 1:
do_something_1();
haveMatched=true;
break;
}
if (haveMatched){
do_finally();
}
I think there might be better way of achieving this (for example, I would've tried the similar way if I hadn't known about the default: keyword). Am I doing it right, or am I missing something?
If you rewrite your code to include a default case you don't have to include haveMatched = true in every case.
var haveMatched=true;
switch (myVar){
case 0:
do_something_0();
break;
case 1:
do_something_1();
break;
default:
haveMatched = false;
}
if (haveMatched){
do_finally();
}
Why not put the function in the case:
switch (myVar){
case 0:
do_something_0();
do_finally();
break;
case 1:
do_something_1();
do_finally();
break;
}
Include the function in every case block, you don't need a flag...
switch (myVar){
case 0:
do_something_0();
do_finally();
break;
case 1:
do_something_1();
do_finally();
break;
}
this is a workaround:
try {
switch (option) {
case 0:
console.log("option 0");
break;
case 1:
console.log("option 1");
break;
default:
}
} catch (err) {
throw err;
} finally {
doActionFinally();
}
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'