Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Javascript support the short ternary (rather, variation of) as in PHP?

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)

like image 554
Dan Lugg Avatar asked Sep 14 '11 04:09

Dan Lugg


People also ask

Does JavaScript support ternary operator?

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.

Can we use ternary operator in PHP?

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.

How does ternary operator work in PHP?

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.

What is '?' In JavaScript?

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.


1 Answers

var data = {     key: value || 'default' }; 
like image 151
Leonid Avatar answered Oct 13 '22 08:10

Leonid