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?
else can be omitted for any if statement, there is nothing special in the last if of an if / else if chain. This is documented in any JavaScript grammar, e.g. in the specification.
Use the ternary operator to use a shorthand for an if else statement. The ternary operator starts with a condition that is followed by a question mark ? , then a value to return if the condition is truthy, a colon : , and a value to return if the condition is falsy. Copied!
The ternary operator, also known as the conditional operator, is used as shorthand for an if...else statement. A ternary operator is written with the syntax of a question mark ( ? ) followed by a colon ( : ), as demonstrated below. In the above statement, the condition is written first, followed by a ? .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With