Javascript shorthand ternary operator

2019-01-21 04:41发布

I know that in php 5.3 instead of using this redundant ternary operator syntax:

startingNum = startingNum ? startingNum : 1

...we can use a shorthand syntax for our ternary operators where applicable:

startingNum = startingNum ?: 1

And I know about the ternary operator in javascript:

startingNum = startingNum ? startingNum : 1

...but is there a shorthand?

Thanks guys!

7条回答
走好不送
2楼-- · 2019-01-21 05:18
var startingNumber = startingNumber || 1;

Something like that what you're looking for, where it defaults if undefined?

var foo = bar || 1; // 1
var bar = 2;
foo = bar || 1;     // 2

By the way, this works for a lot of scenarios, including objects:

var foo = bar || {}; // secure an object is assigned when bar is absent
查看更多
登录 后发表回答