I was working on a JavaScript program, and needed an if statement to assign a value to a variable when a
is larger than b
.
if (a > b) {
c = 11;
}
Is there a better way of doing this?
Originally I thought of using a conditional operator:
(a > b) ? c : 11
But when I log c
to console, it retunes undefined.
I would really appreciate any help/advice on this.
Edit:
I realize that my example did not fully explain what I was trying to achieve. The function takes in seconds, and retunes a string formatted in the from hh:mm:ss. However, I do not what there to be a bunch of leading zeros if the time is less than an hour. I figured out how to do this for the minutes, using a substring if the number minutes is less than ten. I want the same four hours, but am not sure how.
function get_Time_String(seconds) {
date = new Date(0);
date.setSeconds(seconds);
var a = 10 > date.getMinutes() ? 15 : 14;
if (date.getHours() > 16) {
a = 11
}
return date.toISOString().substring(a, 19);
}
4
Answers
write it like this
The reason why undifind c is that you did not define c as var or let before
What you tried using was a ternary operator:
result = (condition)? var1 : var2
This checks the condition. If true, then result is assigned var1, else it is assigned var2. So this is actually equivalent to:
var z;
if (condition) z = var1; else z = var2;
In your case,
(a > b) ? c : 11
returnsc
when conditiona>b
is true, else it returns11
You are not assigning anything to
c
, hence it shows undefined.Try using
var c = (a>b)? 11 : some other value
This assigns 11 to
c
whena>b
, else assign some other value that you want.It’s the same as
No, there’s not.
The only option to reassign a value to
c
only ifa
is bigger thanb
, would bea > b && (c = 11)
. Since this is less readable, use the if statement.