Javascript shorthand ternary operator-ThrowExceptions

Exception or error:

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?

How to solve:
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

###

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

startingNum = startingNum || 1;

###

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.

###

var startingNum = startingNum || 1;

In this case, you can use the OR operator.

###

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.

###

startingNum = startingNum || 1

If you have a condition with null, like

startingNum = startingNum ? startingNum : null

you can use ‘&&’

startingNum = startingNum && startingNum

###

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"

Leave a Reply

Your email address will not be published. Required fields are marked *