Test if a variable is a number

I found that to test if a variable is a number you can do:

!isNaN() or
typeof () === "number"

Yet, when the character is an empty space " " or even a string with nothing “”, the !isNaN() method fails:

let x = 3;
console.log(!isNaN(x));
console.log(typeof x === "number");

// true
// true

let y = " ";
console.log(!isNaN(y));
console.log(typeof y === "number");

// true
// false

let y = "";
console.log(!isNaN(y));
console.log(typeof y === "number");

// true
// false

Why is this?

It is explained in the docs here: isNaN() - JavaScript | MDN

When the argument to the isNaN() function is not of type Number, the value is first coerced to a number, and the resulting value is then compared against NaN.

This behavior of isNaN() for non-numeric arguments can be confusing! For example, an empty string is coerced to 0…

1 Like

coercion… coercion…

But of course!

Many thanks!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.