Javascript if else shorthand

Can I write the 'if else' shorthand without the else?

eg:

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 js.


This is also an option:

x == 2 && dosomething();

dosomething() will only be called if x == 2 . 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 approach instead:

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 thousands of JS compressors. (I recommend Google's Closure Compiler)


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, eg:

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

另外一个选择:

x === 2 ? doSomething() : void 0;
链接地址: http://www.djcxy.com/p/19444.html

上一篇: 如何在javascript中处理'undefined'

下一篇: Javascript如果其他速记