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
Why Does a Regexp With Global Flag Give Wrong Results
Ways to Deal With #Document Under Iframe
How to Detect Safari, Chrome, Ie, Firefox and Opera Browsers
How to Create and Read a Value from Cookie With JavaScript
How Does the "This" Keyword in JavaScript Act Within an Object Literal
Remove Empty Elements from an Array in JavaScript
Xml Parsing of a Variable String in JavaScript
Difference Between Null and Undefined in JavaScript
++Somevariable Vs. Somevariable++ in JavaScript
Do Let Statements Create Properties on the Global Object
Parsing a String to a Date in JavaScript
How to Access the Contents of an Iframe With JavaScript/Jquery
How to Make the First Letter of a String Uppercase in JavaScript
Updating a Nested Array With Mongodb
Getting the Id of the Element That Fired an Event
How to Force Js to Do Math Instead of Putting Two Strings Together