a = (a == b) ? c: b;
I don't understand. All of them {a, b, c} are variables set with certain value by the programmer.
a = (a == b) ? c: b;
I don't understand. All of them {a, b, c} are variables set with certain value by the programmer.
That is called the ternary operator: that is the same as doing:
if(a == b)
a = c;
else
a = b;
This is a short form for an if and an assignment.
q = x ? y : z
q is the variable you assign to x is a boolean expression which will be true or false. If it is true y will be assigned to your variable q else z will be assigned to q.
This is the ternary operator, which is equivalent to:
if (a == b) {
a = c;
} else {
a = b;
}
The main difference is that if/else
consists of conditional statements, while the ternary operator is a conditional expression. In other words, the ternary operator works as if the if/else were returning a value. In some other languages, if/else
are expressions as well, so the following would be valid, and indeed equivalent to ?:
:
a = (if (a == b) { c; } else { b; }) // not valid javascript
Be sure to check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
The Mozilla Developer Network is a fantastic reference for JavaScript.
The ?: syntax is a ternary operator. Essentially it means that if a
is equal to b
than a
equals c
otherwise a
equals b