Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is this if statement not affected by my input?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"))

>Solution :

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(':');
}
function conversionTime(s)
  {
  if (temp[0] >= 01 && temp[0] <= 12);
    {
    temp[0] = Number(temp[0]) + 12;
    return temp.join(':');
    }
  }
console.log(conversionTime("25:05:45PM"))

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading