Home > Blockchain >  simplify number validation in if statement JavaScript
simplify number validation in if statement JavaScript

Time:05-30

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?

CodePudding user response:

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);
}

CodePudding user response:

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?

CodePudding user response:

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

  • Related