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.
The ternary operator, also known as the conditional operator, is used as shorthand for an if...else statement. A ternary operator is written with the syntax of a question mark ( ? ) followed by a colon ( : ), as demonstrated below. In the above statement, the condition is written first, followed by a ? .
Use the ternary operator to use a shorthand for an if else statement. The ternary operator starts with a condition that is followed by a question mark ? , then a value to return if the condition is truthy, a colon : , and a value to return if the condition is falsy. Copied!
When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, x , where x is a number. If the value is omitted, undefined is returned instead.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With