JavaScript shorthand ternary operator JavaScript shorthand ternary operator javascript javascript

JavaScript shorthand ternary operator


var startingNumber = startingNumber || 1;

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

var foo = bar || 1; // 1var 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.