466

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

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
muudless
  • 6,744
  • 7
  • 34
  • 56
  • 2
    Those are operators. The operands are the values you use these operators with. – BoltClock Jun 07 '11 at 02:18
  • 8
    Fun fact: some languages (namely [Groovy](http://groovy.codehaus.org/)) actually have an operand `?:` (as you've written it, with no statement between) - the [Elvis operator](http://groovy.codehaus.org/Operators#Operators-ElvisOperator%28%3F%3A%29). Pretty clever. – Rob Hruska Jun 07 '11 at 02:33
  • 1
    possible duplicate of [javascript if alternative](http://stackoverflow.com/questions/1688337/javascript-if-alternative) – Rob Hruska Jun 07 '11 at 02:35
  • 3
    Googling symbols can be problematic, but how about Googling "Javascript operators" (and learning them all)? – nnnnnn Jun 07 '11 at 07:37
  • check this wiki entry https://en.wikipedia.org/wiki/Elvis_operator – Nerdroid Aug 14 '15 at 00:30

18 Answers18

702

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.

CertainPerformance
  • 260,466
  • 31
  • 181
  • 209
Peter Olson
  • 121,487
  • 47
  • 188
  • 235
  • 63
    Just to clarify the name: `ternary` is the *type* of operator (i.e. it has 3 parts). The name of *that specific ternary operator* is the `conditional operator`. There just happens to only be one ternary operator in JS so the terms get misused. – Gone Coding Nov 10 '14 at 10:12
  • 1
    @tryingToGetProgrammingStraight ternary form is technically an expression, and expressions can contain other expressions to form expression trees. that code right there is what an expression tree looks like :) see: http://fsharpforfunandprofit.com/posts/expressions-vs-statements/ – Alexander Troup Nov 15 '15 at 13:00
  • 2
    Strongly recommend updating the example for the common use case, not a side-effect use case frequently cited as an abusage of the operator. – T.J. Crowder Sep 15 '16 at 18:30
  • 8
    Not sure why there is a little grammar blurb at the bottom, but it is incorrect. If javascript only has 1 of a type of operator, then it is definitely correct to say THE ternary operator and not A ternary operator... Saying "this ternary operator is A ternary operator in javascript (and it is the only one)" is silly, just use THE and it implies all of that. – Andrew Feb 17 '17 at 14:30
  • So I was optimising some PHP and I came across a blog post that showed a ternary being used to assign a value as such, `$somevar = $value['val'] ?: 'N/a'` Which uses the evaluator as the value for true. Does anyone know if we can do the like in JS? which would essentially be like; `someJSVar = data.node ?: 'N/A'` – Mark Carpenter Jr Oct 18 '17 at 13:59
  • 1
    @MarkCarpenterJr In JavaScript the typical way to do that is with the `||` operator, since it short-circuits if the value on the left is truthy. – Peter Olson Oct 18 '17 at 14:11
  • @PeterOlson So `someJSVar = data.node || 'N/A'` ? Edit-- I see it in the answer below... That's pretty sweet! – Mark Carpenter Jr Oct 18 '17 at 14:58
  • ayyo i got a fake id dough.. yes, that is an old song – GavinBelson May 22 '20 at 04:14
159

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.

Jeffrey Roosendaal
  • 5,961
  • 8
  • 33
  • 50
  • 6
    I was struggling with ternary and eventually found this answer. Thank you! – Ljubisa Livac Jul 28 '17 at 19:27
  • If I were not to use the braces around the ternary operator in `'Hello ' + (username ? username : 'guest')`, `Hello + ` if ignored and just the outcome of ternary operation is returned. Can anyone explain why? – Shiva Aug 15 '19 at 16:53
  • 4
    @Shiva Without the brackes, it evalutes the *whole* left part: `'Hello ' + username`, which is always `true`, because it's a string with a length greater than 0. – Jeffrey Roosendaal Aug 15 '19 at 23:00
25

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:

Community
  • 1
  • 1
Michael Robinson
  • 27,775
  • 10
  • 102
  • 126
24

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: Mozilla Developer Center'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;
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
David Tang
  • 86,742
  • 28
  • 159
  • 145
  • Good explanation, but the example is poor since it is assigning a boolean value depending on the outcome of a boolean expression, which makes little sense. You'd rather like to use `var olderThan20 = age > 20;` instead. – BalusC Jun 07 '11 at 02:15
  • @BalusC - yes :) I realised that, but examples are hard to pull out of my hat! Will think of a better one... – David Tang Jun 07 '11 at 02:17
13

Most of the answers are correct but I want to add little more. The ternary operator is right-associative, which means it can be chained in the following way if … else-if … else-if … else :

function example() {
    return condition1 ? value1
         : condition2 ? value2
         : condition3 ? value3
         : value4;
}

Equivalent to:

function example() {
    if (condition1) { return value1; }
    else if (condition2) { return value2; }
    else if (condition3) { return value3; }
    else { return value4; }
}

More details is here

Arif
  • 4,274
  • 3
  • 40
  • 64
  • 2
    This is what I am searching for. – Sazal Das Feb 08 '19 at 01:17
  • I landed here while wondering if there's any compatibility issue in using the chained format which could lead to any side-effect as it used to be for nested ternary operators. It seems to be fully supported since its born, don't know if you have any additional info. – Brigo Oct 11 '20 at 09:04
9
z = (x == y ? 1 : 2);

is equivalent to

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

except, of course, it's shorter.

Ernest Friedman-Hill
  • 77,245
  • 10
  • 138
  • 182
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.

Simplans
  • 1,993
  • 1
  • 20
  • 22
5

Hey mate just remember js works by evaluating to either true or false, right?

let's take a ternary operator :

questionAnswered ? "Awesome!" : "damn" ;

First, js checks whether questionAnswered is true or false.

if true ( ? ) you will get "Awesome!"

else ( : ) you will get "damn";

Hope this helps friend :)

Guy Keren
  • 51
  • 1
  • 4
5

It is called the ternary operator

tmp = (foo==1 ? true : false);
eagle12
  • 1,607
  • 11
  • 14
2
x = 9
y = 8

unary

++x
--x

Binary

z = x + y

Ternary

2>3 ? true : false;
2<3 ? true : false;
2<3 ? "2 is lesser than 3" : "2 is greater than 3";
Gajendra D Ambi
  • 2,634
  • 20
  • 23
2

It's an if statement all on one line.

So

var x=1;
(x == 1) ? y="true" : y="false";
alert(y);

The expression to be evaluated is in the ( )

If it matches true, execute the code after the ?

If it matches false, execute the code after the :

Jason Gennaro
  • 32,917
  • 6
  • 59
  • 84
1

The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.

condition ? expr1 : expr2 

If condition is true, the operator returns the value of expr1; otherwise, it returns the value of expr2.

function fact(n) {
  if (n > 1) {
    return n * fact(n-1);
  } else {
    return 1;
  }
  // we can replace the above code in a single line of code as below
  //return (n != 1) ? n * fact(n - 1) : 1;
}
console.log(fact(5));

For more clarification please read MDN document link

Srikrushna
  • 2,652
  • 30
  • 37
1

We can use with Jquery as well as length as below example :

Suppose we have GuarantorName textbox which has value and want to get firstname and lastname- it may be null. So rathar than

        var gnamesplit = $("#txtGuarantorName").val().split(" ");
        var gLastName = "";
        var gFirstName = "";
        if(gnamesplit.length > 0 ){
           gLastName  = gnamesplit[0];        
        }
        if(gnamesplit.length > 1 ){
           gFirstName = gnamesplit[1];        
        }

We can use below code with Jquery with minimum code

    

    var gnamesplit = $("#txtGuarantorName").val().split(" ");
    var gLastName = gnamesplit.length > 0  ? gnamesplit[0] : "";
    var gFirstName =  gnamesplit.length > 1  ? gnamesplit[1] : "";
    $("#txtLastName").val(gLastName);
    $("#txtFirstName").val(gFirstName);
    
    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div >
  Guarantor Name: <input type="text" id="txtGuarantorName" value="ASP.NET Core"  /><br/>
  <br/>
  <br/>
  
  First Name: <input type="text" id="txtLastName" value="ASP.NET Core"  />
  Last Name: <input type="text" id="txtFirstName" value="ASP.NET Core"  />
</div>
Ajay2707
  • 5,345
  • 6
  • 34
  • 52
1

This is probably not exactly the most elegant way to do this. But for someone who is not familiar with ternary operators, this could prove useful. My personal preference is to do 1-liner fallbacks instead of condition-blocks.

  // var firstName = 'John'; // Undefined
  var lastName = 'Doe';

  // if lastName or firstName is undefined, false, null or empty => fallback to empty string
  lastName = lastName || '';
  firstName = firstName || '';

  var displayName = '';

  // if lastName (or firstName) is undefined, false, null or empty
  // displayName equals 'John' OR 'Doe'

  // if lastName and firstName are not empty
  // a space is inserted between the names
  displayName = (!lastName || !firstName) ? firstName + lastName : firstName + ' ' + lastName;


  // if display name is undefined, false, null or empty => fallback to 'Unnamed'
  displayName = displayName || 'Unnamed';

  console.log(displayName);

Ternary Operator

1

Ternary expressions are very useful in JS, especially React. Here's a simplified answer to the many good, detailed ones provided.

condition ? expressionIfTrue : expressionIfFalse

Think of expressionIfTrue as the OG if statement rendering true;
think of expressionIfFalse as the else statement.

Example:

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

this checked the value of x, the first y=(value) returned if true, the second return after the colon : returned y=(value) if false.

Pang
  • 8,605
  • 144
  • 77
  • 113
PBrook
  • 11
  • 1
1

It's called the ternary operator. For some more info, here's another question I answered regarding this:

How to write an IF else statement without 'else'

Community
  • 1
  • 1
Travis Webb
  • 13,507
  • 6
  • 51
  • 101
  • 5
    Actually ternary is the *type* of operator (i.e. it has 3 parts). The name of *that specific ternary operator* is the `conditional operator`. There just happens to only be one ternary operator in JS so the terms get misused. – Gone Coding Nov 10 '14 at 10:10
0

If you have one condition check instance function in javascript. it's easy to use ternary operator. which will only need one single line to implement. Ex:

    private module : string ='';
    private page:boolean = false;
    async mounted(){
     if(this.module=== 'Main')
    {
    this.page = true;}
    else{
    this.page = false;
    }
}

a function like this with one condition can be written as follow.

this.page = this.module=== 'Main' ?true:false;

condition ? if True : if False

Sunali Bandara
  • 236
  • 2
  • 6
-4
 (sunday == 'True') ? sun="<span class='label label-success'>S</span>" : sun="<span class='label label-danger'>S</span>";

 sun = "<span class='label " + ((sunday === 'True' ? 'label-success' : 'label-danger') + "'>S</span>"
  • you can append html also with ternary operator – Chandrashekhar Komati Mar 31 '17 at 08:56
  • thats really not how you should write ternary assignment and also use === not == other wise you might as well just do `sunday ?`.it should be `sun = "S"` – TheRealMrCrowley May 05 '17 at 18:02
  • the whole point of the conditional ternary is to shorten conditional assignment values otherwise you should just use an if statement – TheRealMrCrowley May 05 '17 at 18:05
  • now tell me this one is correct or not . if you say wrong then still this is working and i am using my project.. – Chandrashekhar Komati May 08 '17 at 07:28
  • I know it "works" how you have it in the first example, but so does what I've provided that you put as the second version. Notice how much unnecessary duplication there is in the top version vs the one I gave you. JS is code that gets sent to the browser, so code length matters – TheRealMrCrowley May 11 '17 at 22:09
  • also if you do sunday == 'True', then if sunday is actually equal to 'False', it conditional is still gonna evaluate to `true` `'True' == 'False'` is `true` but `'True' === 'False'` is false – TheRealMrCrowley May 11 '17 at 22:17
  • @TheRealMrCrowley No, that is wrong. `"True"` is never equal to `"False"`, no matter if you use abstract or strict equality comparison. – Sebastian Simon Dec 11 '20 at 13:57