[ACCEPTED]-How do you read this JavaScript code? (var1 ? var2:var3)-operators

Accepted answer
Score: 17

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

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

var result = condition ? value1 : value2;

Which is equivalent 3 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 2 not a ? and : operator, so ? by itself is meaningless 1 in Javascript.

Score: 6

Its a conditional operator.

It is

if var1 5 then var2 else var3

Read more here

Conditional Operator

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

Score: 2
if(var1) {
    var2;
else {
    var3;
}

0

Score: 2

The expression var1 ? var2 : var3 returns the value of var2 if 23 var1 is considered to have a value equivalent 22 to true else it returns teh value of var3.

Note this 21 is not quite the same as:-

if (var1)
   varX = var2
else
   varX = var3

Since the above 20 construct can not itself appear as part 19 of a larger expression.

In ternery expression, as 18 ? : is known, one should avoid allowing the 17 component expressions to have side effects 16 other than perhaps the side-effects of ++ or 15 -- operators. For example this isn't a 14 good idea:-

varX = var1 ? doSomethingSignificant() : doSomethingElseSignificant();

In this case it would be better 13 to use the if else construct. On the hand:-

varX = var1 ? calcSomething(var2) : someOtherCalc(var2);

this 12 is acceptable assuming the called functions 11 don't themselves modify the program state 10 significantly.

Edit:

I think I need to re-enforce 9 this point. Do not use the ternary operator 8 as means to short cut on if statements. The 7 two have different purposes. If your code 6 is full of ? : that should be if else it will be difficult 5 to read. We expect logical flow to appear in if statements. We 4 expect ? : when there is a simple logical component 3 to an expression. Note expressions do not modify things only 2 the results of them when assigned should 1 modify things.

Score: 2

As an addendum for the first question, you 5 can alternatively use

  var result = (condition) && var1 || var2;

and obtain the same 4 result

For the second question, in C the 3 following works too :

  (condition) && someinstruction;

but that does not seem 2 to work in javascript (at least with my 1 version of firefox).

Score: 1

This seems to be sort of a ternary operation. Short 2 form of an if else operation, so to say. check 1 here for details...

More Related questions