Skip to content Skip to sidebar Skip to footer

Javascript Conditional Return Statement (shorthand If-else Statement)

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

Solution 1:

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:

varvalue = 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(); }

Solution 2:

Well then just write the return in the if

var result = (data && data.cod   ==  '404') 
if (result) {
  return result;
} else {
    //otherwise
}

Post a Comment for "Javascript Conditional Return Statement (shorthand If-else Statement)"