Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I omit the else in an inline javascript if statement?

Tags:

javascript

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(); 
like image 662
evan Avatar asked Feb 10 '12 18:02

evan


People also ask

Can you have an if without an else JavaScript?

You don't need an else statement, you can use ng-if . The ng-if statement is also available without an else condition.

How do you write an inline if in JavaScript?

Method 1: In this method we write an inline IF statement Without else, only by using the statement given below. Method 2: In this method, we will use ternary operator to write inline if statement. Syntax: result = condition ?

Does else if execute after if JavaScript?

if else statements will execute a block of code when the condition in the if statement is truthy . If the condition is falsy , then the else block will be executed.

How do you write the first line of a simple if statement in JavaScript?

“single line if statement javascript” Code Answer'sconsole. log("it is true") : console.


2 Answers

You can use && there:

if_it_is && thats_cool(); 

It is basically equal to:

if (your_expression){    thats_cool(); } 
like image 146
Sarfraz Avatar answered Sep 29 '22 20:09

Sarfraz


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()) { } 
like image 27
Marshall Avatar answered Sep 29 '22 21:09

Marshall