-7

I have a generic JS question that I'm not even sure how to put it.

In what cases do you use the following code structure? What does it mean (or use does this have)? And what is this practice called?

x1 = x2 ? x3 : x4;

Can you give references, examples and possibilities please?

henser
  • 3,181
  • 2
  • 33
  • 44
  • 1
    It's called the [ternary operator](http://en.wikipedia.org/wiki/Ternary_operation). It is a shorthand if-else. It is used in many high-level programming languages. – Mr. Polywhirl Apr 09 '14 at 11:14
  • 2
    @henser—it's *a* [ternary operator](http://en.wikipedia.org/wiki/%3F:), but in ECMAScript it's called the [*conditional operator*](http://ecma-international.org/ecma-262/5.1/#sec-11.12). – RobG Apr 09 '14 at 11:17
  • Got it. Thank you all and sorry for possible duplicate. This is not an easy one to search for without any reference. – henser Apr 09 '14 at 11:25

6 Answers6

0

the following thing

  if(x>10)
  {
      y=10;
  }
  else
  {
      y=9;
  }

can be written as

  (x>10) ? y=10 : y=9;

I think now you understood

King of kings
  • 697
  • 2
  • 6
  • 21
0

if x2 is false, x1 = x4 if x2 is true, x1 = x3

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

user1021605
  • 221
  • 3
  • 14
0

In expanded code this says:

if(x2){
    x1 = x3;
}
else{
    x1 = x4
}

If you're familiar with the ternary operator (if not, look it up) then this might make a lot more sense.

x1 = (x2 ? x3 : x4);
David
  • 4,249
  • 5
  • 27
  • 56
0

It's called the ternary operator. It is a shorthand of if-else. It is used in many high-level programming languages.

x1 = x2 ? x3 : x4;

the above code can be expanded to:

x1 = undefined;

if (x2) {
    x1 = x3;
} else {
    x1 = x4;
}
henser
  • 3,181
  • 2
  • 33
  • 44
Mr. Polywhirl
  • 31,606
  • 11
  • 65
  • 114
0

This is a ternary operator.

if X1 = X2 , X1 takes the value X3 else X1 takes the value X4.

Deepu Sasidharan
  • 4,763
  • 8
  • 32
  • 84
0

? : is a 'ternary operator'; it takes three arguments. The first argument is a test, the second argument is return value if test was true, and the third is a return value if the test was false.

so 1 === 1 ? 'foo' : 'bar' would return 'foo' and 1 === 0 ? 'foo' : 'bar' would return 'bar'. This can always be replaced with an if..else structure, but given its short form it can keep your code uncluttered.

If the test and return values are very complex in form, I would use the more "traditional" if..else structure.

algoni
  • 605
  • 3
  • 8