Omitting the second expression when using the if-else shorthand

Nikki picture Nikki · Jun 17, 2012 · Viewed 650.7k times · Source

Can I write the if else shorthand without the else?

var x=1;

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

I've noticed putting null for the else works (but I have no idea why or if that's a good idea).

Edit: Some of you seem bemused why I'd bother trying this. Rest assured it's purely out of curiosity. I like messing around with JavaScript.

Answer

Nicole picture Nicole · Jun 17, 2012

What you have is a fairly unusual use of the ternary operator. Usually it is used as an expression, not a statement, inside of some other operation, e.g.:

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

So, for readability (because what you are doing is unusual), and because it avoids the "else" that you don't want, I would suggest:

if (x==2) doSomething();