0

I am working on a project, designed by someone else. I came across the following operation. I have no idea what it is doing. It seems to be returning 1.

Anyone care to elaborate? Thank you!

   ( 7  > 8?2:1)
marcoo
  • 821
  • 1
  • 9
  • 25
  • 1
    This is [a quite frequently asked question](http://stackoverflow.com/questions/6259982/js-how-to-use-the-ternary-operator). –  Jul 26 '12 at 14:28

3 Answers3

3

You're looking at the Ternary Operator.

It consists of (condition) ? (expression1) : (expression2). The entire expression will evaluate to (expression1) if (condition) is true, and (expression2) if (condition) is false.

var i = (7 > 8 ? 2 : 1);

translates into

if (7 > 8)
{
  i = 2;
}
else
{
  i = 1;
}
Hans Z
  • 4,664
  • 2
  • 27
  • 50
0

See: http://en.wikipedia.org/wiki/%3F:

Your example would return 2 if 7 > 8, or 1 otherwise.

James M
  • 18,506
  • 3
  • 48
  • 56
0

? : is a ternary operator. This is equivalent to

var x = 0;
if (7 > 8){
  x = 2;
} else {
  x = 1;
}

It is a terse way of expressing simple conditional statements. It is a great way to conditionally assign values to a variable without the verbose semantics used above.

marteljn
  • 6,446
  • 3
  • 30
  • 43