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 imme开发者_如何学编程diately invoked anonymous function, but that seems silly)
var data = {
key: value || 'default'
};
Yes, use ||
. Unlike PHP, JavaScript's ||
operator will return the first non-falsy value, not a normalized boolean.
foo || 'world'
var myFunc = function(foo) {
foo = foo || 'my default value for foo';
}
精彩评论