Coder Perfect

Omitting the second expression when using the if-else shorthand

Problem

Is it possible to express the if else shorthand without including the else?

var x=1;

x==2 ? dosomething() : doNothingButContinueCode();   

I’ve discovered that using null for else works (though I’m not sure why or whether this is a good idea).

Some of you are perplexed as to why I would try this. It’s entirely out of curiosity, so don’t worry. I enjoy tinkering with JavaScript.

Asked by Nikki

Solution #1

This is an interesting application of the ternary operator. It’s usually used as an expression, not a statement, within another process, such as:

var y = (x == 2 ? "yes" : "no");

So, for readability (since what you’re doing is unique), and to prevent the “otherwise” you don’t want, I’d recommend:

if (x==2) doSomething();

Answered by Nicole

Solution #2

This is also a possibility:

x==2 && dosomething();

If x==2 is evaluated to true, dosomething() will be called. Short-circuiting is the technical term for this.

It is rarely used in situations like these, and you should avoid writing code like this. This is a simpler way that I recommend:

if(x==2) dosomething();

If you’re concerned about file size, use one of the various JS compressors to build a minified version of your code. (For instance, Google’s Closure Compiler)

Answered by ajax333221

Solution #3

Another option:

x === 2 ? doSomething() : void 0;

Answered by Buzinas

Solution #4

Why not perform the following if you’re not doing anything else?

if (x==2) doSomething();

Answered by Prescott

Solution #5

For one of the branches of a ternary expression, null is acceptable. In Javascript, a ternary expression can be used as a statement.

However, if you’re writing this to invoke a method, it’s clearer to use if..else:

if (x==2) doSomething;
else doSomethingElse

or, as the case may be,

if (x==2) doSomething;

Answered by Ted Hopp

Post is based on https://stackoverflow.com/questions/11069278/omitting-the-second-expression-when-using-the-if-else-shorthand