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条回答
ら.Afraid
2楼-- · 2019-01-21 05:02

|| will return the first truthy value it encounters, and can therefore be used as a coalescing operator, similar to C#'s ??

startingNum = startingNum || 1;
查看更多
贼婆χ
3楼-- · 2019-01-21 05:04

To make a ternary like:

boolean_condition ? true_result : false_result

in javascript, you can do:

(boolean_condition && true_result ) || false_result;

Example:

(true && 'green') || 'red';
=> "green"
(false && 'green') || 'red';
=> "red"
查看更多
Bombasti
4楼-- · 2019-01-21 05:06

Yes, there is:

var startingNum = startingNum || 1;

In general, expr1 || expr2 works in the following way (as mentioned by the documentation):

Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.

查看更多
beautiful°
5楼-- · 2019-01-21 05:09
startingNum = startingNum || 1

If you have a condition with null, like

startingNum = startingNum ? startingNum : null

you can use '&&'

startingNum = startingNum && startingNum
查看更多
姐就是有狂的资本
6楼-- · 2019-01-21 05:12
var startingNum = startingNum || 1;

In this case, you can use the OR operator.

查看更多
家丑人穷心不美
7楼-- · 2019-01-21 05:13

The above answers are correct. In JavaScript, the following statement:

startingNum = startingNum ? otherNum : 1

can be expressed as

startingNum = otherNum || 1

Another scenario not covered here is if you want the value to return false when not matched. The JavaScript shorthand for this is:

startingNum = startingNum ? otherNum : 0

But it can be expressed as

startingNum = startingNum && otherNum

Just wanted to cover another scenario in case others were looking for a more generalized answer.

查看更多
登录 后发表回答