JavaScript shorthand if statement, without the else portion

Viewed 82365

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?

10 Answers

you can use && operator

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

You can use this shorthand:

if (condition) expression

If in some cases you really want to use the if shorthand. Even though it may not be the best option, it is possible like this.

condition ? fireMe() : ""

Looks weird, does work. Might come in handy in a framework like Vue where you can write this in a template.

You can using Short-circuit Evaluation Shorthand. if you want the if condition just write the else condition.

let 
a = 2,
b = a !== 2 || 'ok';

console.log(b);

Related