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

3

27

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)

Ignatz answered 14/9, 2011 at 4:39 Comment(1)
@NullUserException - I'm using jQuery, and while I do cache my selections, the non-default value is the result of a call to .data(), and I was just looking to avoid a second call using the suggested syntax (and avoid storing the value in a temporary variable)Ignatz
A
49
var data = {
    key: value || 'default'
};
Acidforming answered 14/9, 2011 at 4:42 Comment(6)
Nifty! Thanks @SomeGuy - That seems awfully strange though, that Javascript (read, any language) would return a non-boolean from such a comparison. I mean, I know it's loosely typed, but sheesh.Ignatz
If you are simply trying to allow for default values, $.extend is a very useful function.Woofer
@Bracketworks: The boolean operators don't return booleans in many (especially functional) languages. They will just return one side of the operator (or false).Hendrika
@Hendrika - Thanks, was not aware of this; any examples besides Javascript that come to mind? I'm simply curious.Ignatz
@Bracketworks: Python comes to mind and Lisp. Though probably many more, I just don't know that many languages ;)Hendrika
Keep in mind that this may not always work as expected. For example, if value = 0, then data.key will evaluate to 'default'. This may not be what you want if 0 is a valid value for data.key.Dustproof
R
16

Yes, use ||. Unlike PHP, JavaScript's || operator will return the first non-falsy value, not a normalized boolean.

foo || 'world'
Roveover answered 14/9, 2011 at 4:43 Comment(4)
Thanks @jimbojw - SomeGuy beat ya to it though :)Ignatz
Yeah, well, that's the price I pay for explaining it rather than just writing the answer.Roveover
Yeah, I already edited that out - agree that it was horrible.Roveover
Better explanation than the accepted answer; thanks.Tidal
E
0
var myFunc = function(foo) {
  foo = foo || 'my default value for foo';
}
Elisabetta answered 20/12, 2013 at 11:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.