javascript shorthand if statement, without the else portion

≡放荡痞女 提交于 2019-11-27 07:58:33

you can use && operator - second operand expression is executed only if first is true

direction == "right" && slideOffset += $(".range-slide").width()

in my opinion if(conditon) expression is more readable than condition && expression

Don't think of it like a control-block (ie: an if-else or a switch). It's not really meant for running code inside of it.

You can. It just gets very ugly, very fast, which defeats the purpose.

What you really want to use it for is ASSIGNING VALUES.

Taking your initial example and turning it on its head a little, you get:

direction = (this.dragHandle.hasClass("handle-low")) ? "left" : "right";

See. Now what I've done is I've taken something that would have required an if/else or a switch, which would have been used to assign to that one value, and I've cleaned it up nice and pretty.

You can even do an else-if type of ternary:

y = (x === 2) ? 1 : (x === 3) ? 2 : (x === 4) ? 7 : 1000;

You can also use it to fire code, if you'd like, but it gets really difficult after a while, to know what's going where (see the previous example to see how even assignment can start looking weird at a glance)...

((this.dragHandle.hasClass("...")) ? fireMe(something) : noMe(somethingElse));

...this will typically work.

But it's not really any prettier or more-useful than an if or a branching, immediately-invoking function (and non-JS programmers, or untrained JS programmers are going to crap themselves trying to maintain your code).

The conditional operator is not a shorthand for the if statement. It's an operator, not a statement.

If you use it, you should use it as an operator, not as a statement.

Just use a zero value for the third operand:

slideOffset += direction == "right" ? $(".range-slide").width() : 0;

No, This is not possible, because ternary operator requires, three operands with it.

first-operand ? second-operand (if first evaluates to true) : third-operand (if false)

What you have will not work, but why not just use a one line if statement instead.

if(direction == "right") slideOffset += $(".range-slide").width();

This involves less typing than the method Ray suggested. Of course his answer is valid if you really want to stick to that format.

Dale

This doesn't exactly answer your question, but ternaries allow you to write less than you've shown:

direction = this.dragHandle.hasClass('handle-low') ? "left" : "right";

And now that I think about it, yeah, you can do your question too:

slideOffset + direction == "right" ? = $(".range-slide").width() : = 0;

This is a theory. The next time I have an opportunity to += a ternary I will try this. Let me know how it works!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!