0

I found a script using the following syntax:

var variable3 = (Math.abs(variable1)>Math.abs(variable2)) ? variable1 : variable2;

As far, as I get it, that seems to compare if variable1 is bigger than variable2. Then output, if yes, variable1, otherwise variable2?

I couldn't find any description and this seems to be something handy, could someone explain it?

THX!

R4ttlesnake
  • 1,661
  • 3
  • 18
  • 28
  • see here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator – eladcon Apr 11 '15 at 11:55

4 Answers4

2

This is called the conditional operator (and is the only ternary operator in JavaScript).

It this case it is equivalent to

if((Math.abs(variable1)>Math.abs(variable2)))
{
   variable3= variable1;
}
else
{
   variable3 = variable2;
}
Richard
  • 106,783
  • 21
  • 203
  • 265
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

Its called the "Ternary Operator" Its another way to do a simple in-line if statement and return the value to a variable from it.

See Wikipedia for more info

Xela
  • 2,322
  • 1
  • 17
  • 32
0

it's similar to

if(Math.abs(variable1)>Math.abs(variable2))
    var variable3 =  variable1;
else
    var variable3 =  variable2; 
Abozanona
  • 2,261
  • 1
  • 24
  • 60
0

This is actually a ternary conditional operator (also called a ? mark operator). This is used instead of if statement, but it is as flexible as if statement.

Shuvam Shah
  • 357
  • 2
  • 6
  • 13