Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you read this JavaScript code? (var1 ? var2:var3)

I've seen this format used in JavaScript code, but can't find a good source for the meaning.

Edit for a follow-up:

Thanks for all the quick answers! I figured it was something like that. Now, for bonus points:

can you use (var1 ? var2)

to do the same thing as

    if (var1) {
        var2
    }

?

like image 928
Chris Sobolewski Avatar asked Jul 01 '26 08:07

Chris Sobolewski


2 Answers

It's known as a ternary (because it has three operands) conditional (because it's an if/else/then) operator.

It is evaluated to a value, so you would usually use it to assign a value, such as:

var result = condition ? value1 : value2;

Which is equivalent to:

var result;
if (condition == true) {
  result = value1;
} else {
  result = value2;
}

An example:

var message = "Length is " + len + " " + (len==1 ? "foot" : "feet");

Note ?: is the full operator. It's not a ? and : operator, so ? by itself is meaningless in Javascript.

like image 164
Drew Noakes Avatar answered Jul 02 '26 21:07

Drew Noakes


Its a conditional operator.

It is

if var1 then var2 else var3

Read more here

Conditional Operator

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

like image 44
rahul Avatar answered Jul 02 '26 21:07

rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!