javascript - Omitting the second expression when using the if-else shorthand

ID : 10418

viewed : 30

Tags : javascriptternary-operatorconditional-operatorshorthandjavascript

Top 5 Answer for javascript - Omitting the second expression when using the if-else shorthand

vote vote

93

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(); 
vote vote

85

This is also an option:

x==2 && dosomething(); 

dosomething() will only be called if x==2 is evaluated to true. This is called Short-circuiting.

It is not commonly used in cases like this and you really shouldn't write code like this. I encourage this simpler approach:

if(x==2) dosomething(); 

You should write readable code at all times; if you are worried about file size, just create a minified version of it with help of one of the many JS compressors. (e.g Google's Closure Compiler)

vote vote

73

Another option:

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

67

If you're not doing the else, why not do:

if (x==2) doSomething(); 
vote vote

54

Using null is fine for one of the branches of a ternary expression. And a ternary expression is fine as a statement in Javascript.

As a matter of style, though, if you have in mind invoking a procedure, it's clearer to write this using if..else:

if (x==2) doSomething; else doSomethingElse 

or, in your case,

if (x==2) doSomething; 

Top 3 video Explaining javascript - Omitting the second expression when using the if-else shorthand

Related QUESTION?