javascript shorthand if statement, without the else portion

ahren picture ahren · Jul 19, 2012 · Viewed 59.7k times · Source

So I'm using a shorthand javascript if/else statement (I read somewhere they're called Ternary statements?)

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

This works great, but what if later I want to use just a shorthand if, without the else portion. Like:

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

is this possible at all?

Answer

Andrey Sidorov picture Andrey Sidorov · Jul 19, 2012

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