25
votes

I'm trying to use this and it doesn't appear to be working. I'm guessing it's just not an option, but want to confirm. Is this valid?

(if_it_is) ? thats_cool();
7
No, it's not optional. Use a binary operator instead (&&) as long as thats_cool() returns a value that evaluates to true. - Jonathan M
Nope. It needs to have the : and some value following it. If you want, you could just create a function named do_nothing() that...well, does nothing. - Edwin
user1048967, That is called if() {}. - Dykam
@Jonathan It doesn't have to return boolean, as it'll be called if if_it_is evaluates to a truthy statement. - Edwin
@Edwin, that's a good catch. Thanks. - Jonathan M

7 Answers

50
votes

You can use && there:

if_it_is && thats_cool();

It is basically equal to:

if (your_expression){
   thats_cool();
}
5
votes

What you are trying to use is a Ternary Operator. You are missing the else part of it.

You could do something like:

(if_it_is) ? thats_cool() : function(){};

or

(if_it_is) ? thats_cool() : null;

Or, as others have suggested, you can avoid the ternary if you don't care about the else.

if_it_is && thats_cool();

In JavaScript, as well as most languages, these logical checks step from left to right. So it will first see if if_it_is is a 'trusy' value (true, 1, a string other than '', et cetera). If that doesn't pass then it doesn't do the rest of the statement. If it does pass then it will execute thats_cool as the next check in the logic.

Think of it as the part inside of an if statement. Without the if. So it's kind of a shorthand of

if (if_it_is && thats_cool()) { }
4
votes

No, it's not valid.

The conditional operator takes the form x ? y : z. The third operand is not like the else in an if, it always has to be there.

2
votes

You can't accomplish that using the ternary operator, but you can use the short-circuit nature of && to do what you want.

(if_it_is) && thats_cool();
1
votes

No, you can't. ?: is a ternary operator and MUST have all three of its operands.

1
votes

No, you can't. It's not an "inline if statement", it's the ternary operator, and that is, well… ternary.

(if_it_is) ? thats_cool() : null;

Since you do not seem to be interested in the return value of the operation, you could just write:

if (if_it_is) thats_cool();

though. That would also be better style than using a ternary.

0
votes

You miss the third component. Should be something like that:

(if_it_is) ? thats_cool() : not_too_cool();

The whole sense is:

condition ? do_something_if_condition_is_true : do_something_if_condition_is_false;