I am practicing this Clock tutorial.
Everything in the code is clear to me.
Accept this hr = hr>=12 ? hr-12 : hr;
is not clear me. May be it's a if else
statement.
Can any explain what this code is doing?
Thanks :)
I am practicing this https://developer.mozilla/en/Canvas_tutorial/Basic_animations Clock tutorial.
Everything in the code is clear to me.
Accept this hr = hr>=12 ? hr-12 : hr;
is not clear me. May be it's a if else
statement.
Can any explain what this code is doing?
Thanks :)
Share Improve this question edited Jan 16, 2020 at 6:20 sandeep asked Jun 15, 2012 at 6:30 sandeepsandeep 92.9k24 gold badges140 silver badges156 bronze badges8 Answers
Reset to default 4This is the ternary operator (?:)
Here is the simple explanation of what is being done here:
if(hr>=12)
{
hr=hr-12;
}
//or else hr will have its same value
if (hr >= 12) {
hr = hr - 12;
}
if hr
does not meet that criteria hr
should effectively be left untouched.
its called Ternary operation
It means
if(hr>=12)
hr=hr-12;
else
hr=hr;
the following is enough
if(hr>=12)
hr=hr-12;
It's a ternary operator, of the form:
condition ? if_true | if_false
If you add more brackets for readibility, it can bee:
hr = ( (hr >= 12) ? (hr - 12) : hr )
That is, if more than 12, subtract 12, and store back to hr.
hr= hr>=12 ? hr-12 : hr;
is same to if( hr >= 12 ) hr = hr-12 else hr = hr;
the bool ? expr_a : expr_b
is a operator that when bool
is true, expr_a is evaluated and its value will be used as the whole expr's value, otherwise the expr_b will be.
It means:
if(hr>=12)
{
hr = hr - 12;
}
Generally:
x= condition ? y : z
if condition is true, then x = y
, else x = z
It has same effect as this:
hr %= 12; //equivalent to -> hr = hr>=12 ? hr-12 : hr;
It's called a ternary operator.