You are looking at the conditional operator. It is a ternary operator (operator that takes 3 operands), somewhat similar in function to the if statement.
var y = (x > 0) ? x : -x // parenthesis for extra clarity
is almost equivalent to this:
var y;
if (x>0) {
y = x;
} else {
y = -x;
}
A plain text translation is that if the value before the ? evaluates to true, the expression is evaluates to the value before the :
, otherwise it is evaluated to value after the :
.
The conditional operator doesn't need to be used in assignments only. This piece of code does one or another thing depending if x is larger than 0 or not.
x > 0 ? doOneThing(x) : doAnotherThing(x);
However, due to the overlapping functionality with the if statement (explained above), in cases like this, it is often avoided because it is not as clear. In assignments, like the one mentioned in the first example it is clearer and more concise. The if would have some code repetition (y =
) and both branches need to be examined before identifying that that if just assigns a value to y
. With the conditional operator that fact is immediately apparent.