JavaScript shorthand ternary operator

JavascriptConditional Operator

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

startingNum = startingNum || 1;

Solution 3 - Javascript

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.

Solution 4 - Javascript

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.

Solution 5 - Javascript

In most modern browsers you can now use:

startingNum ??= 1;

This will only change startingNum if it is null or undefined.

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_nullish_assignment

Solution 6 - Javascript

var startingNum = startingNum || 1;

In this case, you can use the OR operator.

Solution 7 - Javascript

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.

Solution 8 - Javascript

startingNum = startingNum || 1

If you have a condition with null, like

startingNum = startingNum ? startingNum : null

you can use '&&'

startingNum = startingNum && startingNum

Solution 9 - Javascript

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"

Solution 10 - Javascript

You can use the accepted answer, but it's not ideal as it breaks when used with bools, if you're defaulting to true, it will always evaluate to true ->

var undefinedVal: boolean;
var trueVal = true;
var falseVal = false;

Angular Template ex:

Value : {{ undefinedVal || true }} -> true
Value : {{ trueVal || true }} -> true
Value : {{ falseVal || true }} -> true?

So use the long way when using bools:

Value : {{ (val != null) ? val : true }}

Also note for typescript and C# (I think), when using ternary with string concatenation it has to be in brackets ->

console.log("Value :" + ((val != null) ? val : true));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWeb_DesignerView Question on Stackoverflow
Solution 1 - JavascriptBrad ChristieView Answer on Stackoverflow
Solution 2 - JavascriptAdam RackisView Answer on Stackoverflow
Solution 3 - JavascriptTadeckView Answer on Stackoverflow
Solution 4 - JavascriptJoshuView Answer on Stackoverflow
Solution 5 - Javascriptuser3336882View Answer on Stackoverflow
Solution 6 - JavascriptDanielView Answer on Stackoverflow
Solution 7 - JavascriptJohn PaceView Answer on Stackoverflow
Solution 8 - Javascripta2441918View Answer on Stackoverflow
Solution 9 - JavascriptxxjjnnView Answer on Stackoverflow
Solution 10 - JavascriptFeargal KavanaghView Answer on Stackoverflow