Cannot read property 'done' of undefined due to switch - javascript

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);
});
}
}

Related

Why is my switch case not working in JavaScript?

I want the variable CurrectcoinValue will get the value of the correct case, but it's not working.
const CurrectcoinValue = "null";
const symbol = "usdt";
casim(symbol, CurrectcoinValue);
console.log("result : " + CurrectcoinValue);
function casim(symbol, CurrectcoinValue) {
switch (symbol) {
case "btc":
CurrectcoinValue = "BTC";
break;
case "eth":
CurrectcoinValue = "ETH";
break;
case "usdt":
CurrectcoinValue = "USDT";
break;
case "usdc":
CurrectcoinValue = "USDC";
break;
default:
CurrectcoinValue = 1;
}
}
There are 2 fundamental problems with your solution:
If you want to be able to change a variable, you need to declare it with let or var (preferably let because the scope is tighter). const is used when explicitly you don't want a variable to be changed.
You can't set a string variable from within a function, JS won't change that variable since it doesn't keep a reference to it!
Also, i think that we have a better way to treat this, which is using a function that does not change any parameter reference, only calculating the value:
const symbol = "usdt";
const CurrectcoinValue = casim(symbol);
console.log("result : " + result);
function casim(symbol) {
switch (symbol) {
case "btc":
return "BTC";
case "eth":
return "ETH";
case "usdt":
return "USDT";
case "usdc":
return "USDC";
default:
return 1;
}
}
This way you are not battling with reference issues.
You could also take the advice of using the symbol.toUpperCase(); method for the cases that are not the default, that would save some code repetition :)

Switch statement not behaving like it should

so i have a piece of code where i have an array (ar=[1,2,3,4,5]) and two functions. the functions are supposed to do the exact same thing: print out something if 1 exists in the array. but function func is always returning "nope" instead of "one" but function another always return the right thing. the only difference between the two functions is function func have a switch instead of an if/else. why? in the source code there are about 12 cases so i actually need to use the switch.
var ar=[1,2,3,4,5];
function func(num){
var one=num;
switch (one) {
case one===1:
console.log("one");
break;
default:
console.log("nope");
break;
}
}
function another (num) {
if(num===2){
console.log("found two");
} else if(num===3){
console.log("found thre");
} else{
console.log("nope");
}
}
ar.forEach(func);
ar.forEach(another);
You have to use the value you want to compare to one
hence
case 1:
instead of
case one===1
here's a fiddle
https://jsfiddle.net/cunx1ono/
Easiest way. Change the switch param to true if you want to use a comparison in the case, because one===1 returns true/false. This is why you always get "nope".
var ar=[1,2,3,4,5];
function func(num){
var one=num;
switch (true) {
case one===1:
console.log("one");
break;
default:
console.log("nope");
break;
}
}

Unreachable code error when I use a break in my switch statement

I am wondering what I am doing wrong in my code. I am trying to do the following:
switch (action.type) {
case TYPES.ADD_TO_FAVORITES:
if (state.faves.length <= 10) {
return assign({}, state, {
faves: state.faves.concat(action.payload),
full: false
});
} else {
return assign({}, state, {
faves: state.faves,
full: true
});
}
default:
return state;
}
My linter says to add a break before default case, but when I do that, it says unreachable code.
The linter rule i.e. 'no-fallthrough' in eslint, acts as to not allow any accidental fallthrough from case to case.
Meaning without break code execution will continue from matching case to next cases unless a break, return etc is encountered.
Sometimes we do need this but unintentional fallthrough can happen and this rule tries to prevent that.
You can disable the rule or configure it as warning .
I would recommend to have a variable assigned for return value and at the end of the function and return it without disabling the rule.
function() {
var returnvalue;
Switch(variableA) {
Case 1:
returnvalue = somevalue;
break;
case 2:
returnvalue = some other value;
break;
default:
returnvalue= default value;
}
return returnvalue;
}
And for the unreachable part, you are returning from your if else block.
So the break will never get any chance to execute.
switch (action.type) {
case TYPES.ADD_TO_FAVORITES:
if (state.faves.length <= 10) {
return ...;
} else {
return ...;
}
break; // YOU HAVE ADDED BREAK HERE
default:
return state;
}
Inside case TYPES.ADD_TO_FAVORITES, either if or else will be executed. As in both if and else you have returned some object, the break you have added just before default, will never going to be executed!
That's why it says it says unreachable code.
Return in switch statement make no sense and not allowed. You can only return in a function. If you want to get value back from switch statement. Just assign it to a variable like this
var result;
switch (action.type) {
case TYPES.ADD_TO_FAVORITES:
if (state.faves.length <= 10) {
result = assign({}, state, {
faves: state.faves.concat(action.payload),
full: false
});
} else {
result = assign({}, state, {
faves: state.faves,
full: true
});
}
break;
default:
result = state;
break;
}

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
}

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