Vivek Pratap Singh
Vivek Pratap Singh

Reputation: 9974

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 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.

Upvotes: 9

Views: 36713

Answers (2)

JLRishe
JLRishe

Reputation: 101662

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

Upvotes: 19

Ba5t14n
Ba5t14n

Reputation: 739

Well then just write the return in the if

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

Upvotes: 1

Related Questions