Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

187
Views
simplify number validation in if statement JavaScript

I am validating my time in this way

if (
  timeInMins != 0 &&
  timeInMins != "0" &&
  timeInMins != undefined &&
  timeInMins != "undefined" &&
  timeInMins != null &&
  timeInMins != "" &&
  !isNaN(timeInMins)
) {
  timeInMinsCumulative += parseFloat(timeInMins);
}

Is there any way to make this ugly if-check to sophisticated code?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

This uses the coercion behavior of JavaScript and the logical AND operator to simplify your code. The following is very nearly equivalent to your code, but it will also guard against the arguments false and 0n.

if (timeInMins &&
    timeInMins !== '0' &&
    timeInMins !== 'undefined') {
  // whatever          
}

Questions for you: do you really expect to ever get the string 'undefined' passed to you? Why do you want to guard against '0' being sent to parseFloat? Are you sure parseInt is not what you want?

about 4 years ago · Juan Pablo Isaza Report

0

There are 6 falsy values in javascript: undefined, null, NaN, 0, "" (empty string), and false of course.

So, you can just write

if (timeInMins && timeInMin !== '0') {
          timeInMinsCumulative += parseFloat(timeInMins);
}
about 4 years ago · Juan Pablo Isaza Report

0

It seems you want to check if timeInMins is precise Number type or not.

function isValidNumber(num) {
  return typeof num === "number" && !isNaN(num);
}

console.log(isValidNumber(""));
console.log(isValidNumber(undefined));
console.log(isValidNumber(NaN));
console.log(isValidNumber("undefined"));
console.log(isValidNumber(true));
console.log(isValidNumber(false));
console.log(isValidNumber(0));
console.log(isValidNumber("0"));
console.log(isValidNumber(1.234));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!