How to Use the : (Conditional) Operator in JavaScript

How do you use the ? : (conditional) operator in JavaScript?

This is a one-line shorthand for an if-else statement. It's called the conditional operator.1

Here is an example of code that could be shortened with the conditional operator:

var userType;
if (userIsYoungerThan18) {
userType = "Minor";
} else {
userType = "Adult";
}

if (userIsYoungerThan21) {
serveDrink("Grape Juice");
} else {
serveDrink("Wine");
}

This can be shortened with the ?: like so:

var userType = userIsYoungerThan18 ? "Minor" : "Adult";

serveDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine");

Like all expressions, the conditional operator can also be used as a standalone statement with side-effects, though this is unusual outside of minification:

userIsYoungerThan21 ? serveGrapeJuice() : serveWine();

They can even be chained:

serveDrink(userIsYoungerThan4 ? 'Milk' : userIsYoungerThan21 ? 'Grape Juice' : 'Wine');

Be careful, though, or you will end up with convoluted code like this:

var k = a ? (b ? (c ? d : e) : (d ? e : f)) : f ? (g ? h : i) : j;

1 Often called "the ternary operator," but in fact it's just a ternary operator [an operator accepting three operands]. It's the only one JavaScript currently has, though.

JavaScript - conditional operator

As you suggested, by introducing any type of variable in a ternary operator, they are automatically converted to their boolean equivalent.

The two functions are not strictly equivalent because the first one explicitly checks if the variable equals 0, while the second one doesn't, so n will evaluate to false and return 0 if it contains any falsy value like false, '', undefined or whatever else.

function sumTo(n) {
if (n === 0) return 0; // base case
return n + sumTo(n-1); // inductive step
}

sumTo(false); // Uncaught RangeError: Maximum call stack size exceeded

Expansion with conditional ternary operator

Unfortunately this isn’t currently possible. The spread syntax, like its name tells us, is a part of the syntax of the language and not a ‘normal’ operator that deals with expressions (à la + or typeof). The ternary operator needs expressions after the ? and :, so you can’t use the syntax in those spots.

You’ll have to do e.g.

condition
? console.log(…)
: console.log(…)

Conditional (ternary) operator is going directly to else option

let tipoUser = parseInt(sessionStorage.getItem("TipoUser"))

Javascript ternary operator -- what is the condition?

The ternary

counts[ch] = count ? count + 1 : 1;

The condition in this expression is not counts[ch] = count but just count and is equivalent to

if (count){
counts[ch] = count + 1;
}
else {
counts[ch] = 1;
}

The right hand side of an assignment expression is always evaluated first and the counts[ch] is assigned the result of count ? count + 1 ? 1.



Related Topics



Leave a reply



Submit