Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 777
ahren Avatar asked Jul 19 '12 05:07

ahren


People also ask

Can we write else if without else in JavaScript?

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.

How do you shorten an if else statement in JavaScript?

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!

How do you shorten if else statements?

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 ? .


1 Answers

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

like image 144
Andrey Sidorov Avatar answered Sep 23 '22 16:09

Andrey Sidorov