skip to Main Content

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


  1. write it like this
    The reason why undifind c is that you did not define c as var or let before

    var c = (a > b) && 11;
    
    Login or Signup to reply.
  2. 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 returns c when condition a>b is true, else it returns 11

    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 when a>b, else assign some other value that you want.


    Login or Signup to reply.
  3. c = a > b ? 11 : c;
    

    It’s the same as

    if (a > b) {
        c = 11;
    } else {
        c = c;
    }
    
    Login or Signup to reply.
  4. No, there’s not.

    The only option to reassign a value to c only if a is bigger than b, would be a > b && (c = 11). Since this is less readable, use the if statement.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search