Alan2
Alan2

Reputation: 24602

Can I put a call to a function inside my if statement in Javascript?

I have the following code:

var rtn = getParams(entity)
if (rtn.rc == false) { return; }
parameters = rtn.param; 

Is there a way that I can put the call to getParams inside of the if statement? Also do I need to put the return; in braces with javascript? I am looking for a way to clean up this code snippet. Any suggestions would be appreciated.

Upvotes: 1

Views: 80

Answers (3)

Yevgeny Simkin
Yevgeny Simkin

Reputation: 28439

I think what you're after is this...

if(getParams(entity).rc == false)
    return;

 parameters = getParams(entity).params; 

That is perfectly valid (and legal) Javascript.

assuming that getParams returns an Object which has a property of rc, you're good to go. If not, you're going to fail on an uncaught exception for an undefined field (in this case rc).

Also, keep in mind that unlike some other languages false != null and false != undefined and an empty string "" is neither false nor undefined, so make sure rc is *actually false if you want this test to work.

Upvotes: 3

kiranvj
kiranvj

Reputation: 34147

Also do I need to put the return; in braces with javascript?

Not necessary, but its recommended.

I am looking for a way to clean up this code snippet. Replace your 3 lines with this.

parameters = getParams(entity).rc ? getParams(entity).param : false;
return parameters;

Upvotes: 1

Matt Dodge
Matt Dodge

Reputation: 11152

Might as well do it all at once

if ( (rtn = getParams(entity)).rc ) {
    parameters = rtn.param;
} else {
    return;
}

Upvotes: 3

Related Questions