The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
“Question mark” or “conditional” operator in JavaScript is a ternary operator that has three operands. The expression consists of three operands: the condition, value if true and value if false. The evaluation of the condition should result in either true/false or a boolean value.
A question mark by another name The question mark operator ? takes three operands: some condition, a value if that condition is true, and a value if that condition is false. It is used in JavaScript to shorten an if else statement to one line of code.
The question mark after the variable is called Optional chaining (?.) in JavaScript. The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null.
It is called the Conditional Operator (which is a ternary operator).
It has the form of: condition
? value-if-true
: value-if-false
Think of the ?
as "then" and :
as "else".
Your code is equivalent to
if (max != 0)
hsb.s = 255 * delta / max;
else
hsb.s = 0;
Properly parenthesized for clarity, it is
hsb.s = (max != 0) ? (255 * delta / max) : 0;
meaning return either
255*delta/max
if max != 00
if max == 0This is probably a bit clearer when written with brackets as follows:
hsb.s = (max != 0) ? (255 * delta / max) : 0;
What it does is evaluate the part in the first brackets. If the result is true then the part after the ? and before the : is returned. If it is false, then what follows the : is returned.
hsb.s = max != 0 ? 255 * delta / max : 0;
?
is a ternary operator. It works like an if
in conjunction with the :
!=
means not equals
So, the long form of this line would be
if (max != 0) { //if max is not zero
hsb.s = 255 * delta / max;
} else {
hsb.s = 0;
}
?: is a short-hand condition for else {}
and if(){}
problems.
So your code is interchangeable to this:
if(max != 0){
hsb.s = 225 * delta / max
}
else {
hsb.s = 0
}
MDN - Conditional (Ternary) Operator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With