ggkmath
ggkmath

Reputation: 4246

basic Javascript if/else statement question

I'm looking at the following Javascript code, trying to port it to another language:

if (x>n) {return q} {return 1-q)

I don't know what the code is doing, but can someone tell me based on syntax what occurs? Is there an implied 'else' before the last set of {}? That is, if x>n then return q otherwise return 1-q?

If it helps, here's the line of code it was embedded within:

if(x>9000 | n>6000) { var q=Norm((Power(x/n,2/5)+1/(8*n)-1)/Sqrt(9/(2*n)))/3; if (x>n) {return q}{return 1-q} }

thanks

Upvotes: -1

Views: 1397

Answers (6)

alex
alex

Reputation: 490143

That code is really...

if (x > 9000 | n > 6000) {
    var q = Norm((Power(x / n, 2 / 5) + 1 / (8 * n) - 1) / Sqrt(9 / (2 * n))) / 3;
    if (x > n) {
        return q
    } {
        return 1 - q
    }
}

Either someone thinks unreadable code is a good idea, or they used a bad minifer.

Upvotes: 1

Xavier Holt
Xavier Holt

Reputation: 14621

There's only an implied else because the block that pairs with the if statement returns from the function. The code you posted is equivalent to:

if(x > n)
{
    return q;
}
return q + 1;

You only get if/else-like behaviour because the second statement can only be executed if the first statement isn't (because the first statement would return from the function, and control would never get to the second).

This bad code! For readability / maintainability / sanity, it should be written in one of these more sustainable formats:

if(x > n) {return q;}
else      {return q + 1;}

Or:

return (x > n)? q : q + 1;

Hope that helps!

Upvotes: 2

Delta
Delta

Reputation: 4328

That block of {} after return q is not necessary. there isn't any else statement implied there, it's just that if it passes throught the if statement and return q, what comes next won't be executed anymore, otherwise, it will. Then there is no need to put an else there.

Upvotes: 1

Ken Wayne VanderLinde
Ken Wayne VanderLinde

Reputation: 19339

There is not an implied 'else', the next set of braces simply defines another compound statement. In this case, it acts like an 'else', but only because the 'if' portion carries a return statement.

Upvotes: 2

Amy Anuszewski
Amy Anuszewski

Reputation: 1853

There's an implied else. If x>n, the function returns q. Otherwise, it goes to the next return statement and returns 1-q.

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190907

Its basically this:

if (x>n)
   return q; 
else 
   return 1-q;

Upvotes: 2

Related Questions