So I have a timer variable that points to a paragraph in html.
Now I want to change the contents of this paragraph to display time
timer.innerHTML = hr + ":" + min;
Note: hr and min are variables that store the current time.
So, in order to avoid a situation where the time shows as
"9:7" when it’s 09:07am, I added a bunch of if statements
If(hr < 10){
timer.innerHTML = "0" + hr + ":" + min;
}
If (min < 10){
timer.innerHTML = hr + ":" + min;
}
However, I want to do so for hours, minutes, and seconds aswell.
Is there a more efficient way to do this rather than with a bunch of if statements.
Because it might become quite tedious to write if statements for every possiblity.
>Solution :
Try this, with a ternary conditional operator (see the docs on MDN for help):
time.innerHTML = (hr < 10 ? '0' : '') + hr + ':' + (min < 10 ? '0' : '') + min;
Here’s the MDN documentation for the conditional operator:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator