Search code examples
javascriptif-statementconditional-operatorshorthand

JavaScript shorthand if statement, without the else portion


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?


Solution

  • 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