How do I write shorthand for else if statements?
if (showvar == "instock"){
//show available
} else if (showvar == "final3"){
//show only 3 available
} else {
//show Not available
}
I know to write when there's only if
and else
. But How do I write this when there's an else if
statement?
(showvar == "instock")? //show available : //show Not available
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 ? .
The ternary conditional operator is a short-hand method for writing an if/else statement. There are three components to the ternary operator: the expression/condition, the positive value, and the negative value. When the expression evaluates to true, the positive value is used—otherwise the negative value is used.
Conditional StatementsUse if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.
You simply nest the else if
s on the false
side of :
; else
clauses are simply false
as well. Like so...
(showvar == "instock") ?
show available : ((showvar == "final3") ?
show only 3 available : show Not available);
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