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

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

Can someone please explain to me in simple words what is the ?: (conditional, “ternary”) operator and how to use it?

Solutions/Answers:

Solution 1:

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:

if(userIsYoungerThan21) {
  serveGrapeJuice();
}
else {
  serveWine();
}

This can be shortened with the ?: like so:

userIsYoungerThan21 ? serveGrapeJuice() : serveWine();

In Javascript conditional operator can evaluate to an expression, not just a statement:

var userType = userIsYoungerThan18 ? "Minor" : "Adult";
serveDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine");

They can even be chained:

userIsYoungerThan4 ? serveMilk() : userIsYoungerThan21 ? serveGrapeJuice() : serveWine();

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.

Solution 2:

I want to add some to the given answers.

In case you encounter (or want to use) a ternary in a situation like ‘display a variable if it’s set, else…’, you can make it even shorter, without a ternary.


Instead of:

var welcomeMessage  = 'Hello ' + (username ? username : 'guest');

You can use:

var welcomeMessage  = 'Hello ' + (username || 'guest');

This is Javascripts equivallent of PHP’s shorthand ternary operator ?:

Or even:

var welcomeMessage  = 'Hello ' + (username || something || maybethis || 'guest');

It evaluates the variable, and if it’s false or unset, it goes on to the next.

Solution 3:

It’s called the ‘ternary’ or ‘conditional’ operator.

Example

The ?: operator can be used as a
shortcut for an if…else statement.
It is typically used as part of a
larger expression where an if…else
statement would be awkward. For
example:

var now = new Date();
var greeting = "Good" + ((now.getHours() > 17) ? " evening." : " day.");

The example creates a string
containing “Good evening.” if it is
after 6pm. The equivalent code using
an if…else statement would look as
follows:

var now = new Date();
var greeting = "Good";
if (now.getHours() > 17)
   greeting += " evening.";
else
   greeting += " day.";

From MSDN JS documentation.

Basically it’s a shorthand conditional statement.

Also see:

Solution 4:

It’s a little hard to google when all you have are symbols 😉 The terms to use are “javascript conditional operator”.

If you see any more funny symbols in Javascript, you should try looking up Javascript’s operators first: MDC’s list of operators. The one exception you’re likely to encounter is the $ symbol.

To answer your question, conditional operators replace simple if statements. An example is best:

var insurancePremium = age > 21 ? 100 : 200;

Instead of:

var insurancePremium;

if (age > 21) {
    insurancePremium = 100;
} else {
    insurancePremium = 200;
}

Solution 5:

z = (x == y ? 1 : 2);

is equivalent to

if (x == y)
    z = 1;
else
    z = 2;

except, of course, it’s shorter.

Solution 6:

Ternary Operator

Commonly we have conditional statements in Javascript.

Example:

if (true) {
    console.log(1)
} 
else {
    console.log(0)
}
# Answer
# 1

but it contain two or more lines and cannot assign to a variable.
Javascript have a solution for this Problem Ternary Operator.
Ternary Operator can write in one line and assign to a variable.

Example:

var operator = true ? 1 : 0
console.log(operator)
# Answer
# 1

This Ternary operator is Similar in C programming language.