0

I need a built in function that checks if a variable contains a valid number in Javascript , following this link I've tried to use is isNaN , however when I use one quote ('') or two quotes ("") , the result is always false.

How come one quote or double quotes are considered a valid number ?

JAN
  • 21,236
  • 66
  • 181
  • 318

3 Answers3

1

isNaN()

The empty string is converted to 0 which is not NaN

Mamun
  • 66,969
  • 9
  • 47
  • 59
1

Any thing which cannot be converted to number should return true, But "" string can be parsed to number so it returns false

console.log(+"")
console.log(Number(""))
console.log(isNaN(""))

A polyfill for isNaN looks like this

var isNaN = function(value) {
    var n = Number(value);
    return n !== n;
};

console.log(isNaN(""))

Note:- Things get confusing when you try parseInt on these values. But the parseInt specs literally says it returns NaN the first non-whitespace character cannot be converted to a number. or radix is below 2 or above 36.

console.log(parseInt(""))
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

Converting an empty string to Number will evaluate to 0. Same goes for booleans (+false = 0, +true = 1), and null. If that's unwanted, you can create your own function to determine if some (string) value can be converted to Number. See also (the examples @) MDN.

const canConvert2Number = value =>
      !value ||
      value === false ||
      value === true ||
      value === null || 
      String(value).trim().length < 1
      ? false
      : !isNaN(+value);

console.log(canConvert2Number(null));    //false
console.log(canConvert2Number(""));      //false
console.log(canConvert2Number());        //false
console.log(canConvert2Number(false));   //false
console.log(canConvert2Number(true));    //false
console.log(canConvert2Number("[]"));    //false
console.log(canConvert2Number("{}"));    //false
console.log(canConvert2Number("20.4"));  //true
console.log(canConvert2Number("10E4"));  //true
.as-console-wrapper { top: 0; max-height: 100% !important; }
KooiInc
  • 119,216
  • 31
  • 141
  • 177