Categories
Javascript

4 Ways To Check If A Variable Is A Number In JS + Comparison

Comparison Table

Case/^\d+$/
.test(variable)
/^[0-9]+$/
.test(variable)
!isNaN
(variable)
typeof
variable
“123”TrueTrueTruestring
” “FalseFalseTruestring
123TrueTrueTruenumber
“1.23”FalseFalseTruestring
1.23FalseFalseTruenumber
“abc”FalseFalseFalsestring
Comparison of Different Methods to Find Out if a Variable Is a Number in JS
  • RegexPattern.test(String)
/^[0-9]+$/.test("123")
> True
/^\d+$/.test("123")
> True

  • isNaN: This function works with both numbers and numbers inside strings.
isNaN(10)
> False
isNaN("10")
> False
isNaN(" ") // Considers blank spaces as a number
> False
isNaN("not a number")
> True

When using isNaN to determine if a string is a number, be careful that this function returns false for an empty string or a string with only spaces in it.

  • typeOf : Strictly checks numbers and returns “number” for numeric values.
typeof 10
> "number"
typeof "10"
> "string"

Below is the code I used to compare the methods:

var str = "1.23";
var space = " ";
var num = 123;
var float = 1.23;
var letters = "abc";

console.log(/^\d+$/.test(str));
console.log(/^\d+$/.test(space));
console.log(/^\d+$/.test(num));
console.log(/^\d+$/.test(float));
console.log(/^\d+$/.test(letters));

console.log(/^[0-9]+$/.test(str));
console.log(/^[0-9]+$/.test(space));
console.log(/^[0-9]+$/.test(num));
console.log(/^[0-9]+$/.test(float));
console.log(/^[0-9]+$/.test(letters));

console.log(!isNaN(str));
console.log(!isNaN(space));
console.log(!isNaN(num));
console.log(!isNaN(float));
console.log(!isNaN(letters));

console.log(typeof str);
console.log(typeof space);
console.log(typeof num);
console.log(typeof float);
console.log(typeof letters);

Leave a Reply

Your email address will not be published.