Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In simple words, what is the ?: (conditional, "ternary") operator and how can I use it?

like image 512
muudless Avatar asked Jun 07 '11 02:06

muudless


People also ask

What is the use of a conditional operator give some examples JavaScript?

Example: In the following web document the conditional operator statement [status = (marks >= 30) ? "Pass" : "Fail"] assigns value "Pass" to the variable status if marks are 30 or more. Otherwise, it assigns the value of "Fail" to status.

How do you write conditional in JavaScript?

The keyword if tells JavaScript to start the conditional statement. (10 > 5) is the condition to test, which in this case is true — 10 is greater than 5. The part contained inside curly braces {} is the block of code to run. Because the condition passes, the variable outcome is assigned the value "if block".

Why we use === in JavaScript?

The === operator compares operands and returns true if both operands are of same data type and have some value, otherwise, it returns false. The !== operator compares operands and returns true if both operands are of different data types or are of the same data type but have different values.


1 Answers

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; 

1Often 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.

like image 113
Peter Olson Avatar answered Sep 20 '22 09:09

Peter Olson