I've become fond of PHP's support for the "short ternary", omitting the second expression:
// PHP $foo = 'hello'; $bar = ''; echo $foo ?: 'world'; // hello echo $bar ?: 'world'; // world
Does Javascript support any sort of syntax like this? I've tried ?:
resulting in a syntax error. I'm aware of boolean short circuits, but that's not feasible for what I'm currently doing; that being:
// Javascript var data = { key: value ?: 'default' };
Any suggestions? (I could wrap it in an immediately invoked anonymous function, but that seems silly)
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
The term "ternary operator" refers to an operator that operates on three operands. An operand is a concept that refers to the parts of an expression that it needs. The ternary operator in PHP is the only one that needs three operands: a condition, a true result, and a false result.
ternary operator: The ternary operator (?:) is a conditional operator used to perform a simple comparison or check on a condition having simple statements. It decreases the length of the code performing conditional operations. The order of operation of this operator is from left to right.
It's called the 'ternary' or 'conditional' operator. The ?: operator can be used as a shortcut for an if...else statement. It is typically used as part of a larger expression where an if...else statement would be awkward.
var data = { key: value || 'default' };
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