Home > Software engineering >  Why is this if statement not affected by my input?
Why is this if statement not affected by my input?

Time:10-23

I want to build an algorithm who convert AM/PM to the 24hours format. It's not finished, but the code I have so far is behaving strangely.

When I give the input "25:05:45PM", it should enter the first branch of the first if statement, but should not enter the second if statement. I've checked the condition, and it's definitely false. My brain is melting.

Here is the code :

function conversionTime(s) {
  if (s.includes('PM')) {
    let temp = s.slice(0, 8).split(':');
    if (temp[0] >= 01 && temp[0] <= 12); {
      temp[0] = Number(temp[0])   12;
      return temp.join(':')
    }
  } else if (s.includes('AM')) {
    let temp2 = s.slice(0, 8).split(':');
    return temp2
  }
}
console.log(conversionTime("25:05:45PM"))

CodePudding user response:

Gotcha.

if (temp[0] >= 01 && temp[0] <= 12);

This semicolon is the culprit! It's saying "the if statement is over, no need to do anything", so your code is being interpreted like:

if (temp[0] >= 01 && temp[0] <= 12);

{
  temp[0] = Number(temp[0])   12;
  return temp.join(':');
}

The code in the block will always run. This feature exists so you can make full use of let's scoping:

let x = "outside";
console.log(x);
{
  let x = "inside";
  console.log(x);
}
console.log(x);

Well, really it exists because that's how C works – it predates the let statement – but that's what it's useful for these days.

  • Related