I came across the following line
hsb.s = max != 0 ? 255 * delta / max : 0;
What do the ? and : mean in this context?
I came across the following line
hsb.s = max != 0 ? 255 * delta / max : 0;
What do the ? and : mean in this context?
?: 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
}
What you are referring to is called a ternary operator, it is essentially a basic if condition check that can be written to execute an operation if the block of code within the ternary operation is valid, otherwise default to a fallback.
A ternary operation is written in the following syntax:
condition ? exprIfTrue : exprIfFalse
condition An expression whose value is used as a condition.exprIfTrue An expression which is evaluated if the condition evaluates to a truthy value (one which equals or can be converted to true).exprIfFalse An expression which is executed if the condition is falsy (that is, has a value which can be converted to false).Take the given function below which should return the string Yes if the number provided to the function is even, otherwise return No.
function isEven(num) {
return (num % 2 == 0) ? "Yes" : "No";
}
console.log("2: " + isEven(2));
console.log("3: " + isEven(3));
The operation above broken down:
(num % 2 == 0) | This is a simple if statement condition to check if the expression within the brackets is true.? "Yes" If the operation is true, the string literal given is automatically returned as a result of this execution.: "No" This is the else clause in this operation, if the condition is not met then No is returned.