• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

147
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 3 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 3 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 3 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 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error