Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript shorthand ternary operator

People also ask

How do you chain a ternary operator?

The ternary operator is basically a combination of a question mark and a colon. To use this operator, you need to write a conditional expression, followed by a question mark (?). Then you need to provide two statements or expressions separated by a colon.

Is ternary operator bad practice?

The conditional ternary operator can definitely be overused, and some find it quite unreadable. However, I find that it can be very clean in most situations that a boolean expression is expected, provided that its intent is clear.

Which is better ternary operator or if else?

If the condition is short and the true/false parts are short then a ternary operator is fine, but anything longer tends to be better in an if/else statement (in my opinion).


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.


With the addition of ES2020:

New w/Nullish Coalescence: const difficulty = var?.nest[i]?.prop ?? false

Older Operation: const difficulty = var.nest[i].prop ? var.nest[i].prop : false

The question mark before the property will first check if the object even exists (if you aren't sure it will: like in API data) and, if an object is missing, it will return undefined

The ?? checks if the value on the left is null or undefined and, if it is, will return a supplied value on the right.