Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
124
rated 0 times [  130] [ 6]  / answers: 1 / hits: 31737  / 10 Years ago, fri, january 23, 2015, 12:00:00

While writing shorthand if-else in javascript,getting syntax error. Here is my code:



data && data.cod   ==  '404' && return;


Although works fine when I use normal if-else like below:



        if(data && data.cod   ==  '404') {return};
var temp = data && data.main && data.main.temp;
//Code here...


I know, it works fine if I use ternary operator like return (data && data.cod == '404')?'true':'false'; but I'm looking return on conditional basis otherwise continue further.


More From » jquery

 Answers
18

What you're trying to do is a violation of syntax rules.



The return keyword can only be used at the beginning of a return statement



In data && data.cod == '404' && <something>, the only thing you can place in <something> is an expression, not a statement. You can't put return there.



To return conditionally, use a proper if statement:



if(data && data.cod == '404') {
return;
}


I would recommend against using shortcuts like you're trying to do as a clever way to execute code with side effects. The purpose of the conditional operator and boolean operators is to produce a value:



Good:



var value = condition ? valueWhenTrue : valueWhenFalse;


Bad:



condition ? doSomething() : doSomethingElse();


You shouldn't be doing this, even if the language allows you to do so. That's not what the conditional operator is intended for, and it's confusing for people trying to make sense of your code.



Use a proper if statement for that. That's what it's for:



if (condition) {
doSomething();
} else {
doSomethingElse();
}


You can put it on one line if you really want to:



if (condition) { doSomething(); } else { doSomethingElse(); }

[#68119] Wednesday, January 21, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
eanskylerg

Total Points: 524
Total Questions: 107
Total Answers: 100

Location: Colombia
Member since Mon, May 2, 2022
2 Years ago
;