What’s the best way to check if variable is a number in JavaScript

Javascript is dynamically typed. How can I check if a particular variable is holding a numeric value at run-time?

  1. Accepted Answer

Accepted Answer

Use the Number.isFinite(value) method

The best way to check if the variable is a number is to use the Number.isFinite(value) method. It returns true if the passed value is a finite number, that is,

  1. the value is Number
  2. the value is NOT positive or negative Infinity
  3. the value is NOT NAN.

Here are some examples in Node.js:

console.log(Number.isFinite(10)); 		// true
console.log(Number.isFinite(-10)); 		// true
console.log(Number.isFinite(3.5)); 		// true

console.log(Number.isFinite(1/0));		// false
console.log(Number.isFinite(true));		// false
console.log(Number.isFinite(undefined));	// false
console.log(Number.isFinite(NaN));		// false
console.log(Number.isFinite("codeahoy.com")); // false

typeof Operator

An alternate way to check if a variable is a number is to use the typeof operator. It returns a string indicating the type of operand. It correctly handles undefined, NaN and null values.

console.log(typeof 10); 	// "number"
console.log(typeof true);	// "boolean"
console.log(typeof undefined); 	// "undefined"
console.log(typeof 1/0);	// "NaN"
console.log(typeof null);	// "object"

isNaN(value) Method

Another non-recommended way to check if a variable is a number is to use the isNaN() method. NaN stands for Not a Number so we’ll use the ! operator in our checks.

The issue is that it returns true for Infinity and null (technically these are special values, not numbers,) so avoid this method if you can.

console.log(!isNaN(10)); // true
console.log(!isNaN(3.5)); // true
console.log(!isNaN(1/0)); // true; should be false because Infinity
console.log(!isNaN(null)); // true; should be false because null
console.log(!isNaN("codeahoy.com")); // false

Speak Your Mind