Check whether variable is number or string in JavaScript

Solution 1:

If you're dealing with literal notation, and not constructors, you can use typeof:.

typeof "Hello World"; // string
typeof 123;           // number

If you're creating numbers and strings via a constructor, such as var foo = new String("foo"), you should keep in mind that typeof may return object for foo.

Perhaps a more foolproof method of checking the type would be to utilize the method found in underscore.js (annotated source can be found here),

var toString = Object.prototype.toString;

_.isString = function (obj) {
  return toString.call(obj) == '[object String]';
}

This returns a boolean true for the following:

_.isString("Jonathan"); // true
_.isString(new String("Jonathan")); // true

Solution 2:

Best way to do that is using isNaN + type casting:

Updated all-in method:

function isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) }

The same using regex:

function isNumber(n) { return /^-?[\d.]+(?:e-?\d+)?$/.test(n); } 

------------------------

isNumber('123'); // true  
isNumber('123abc'); // false  
isNumber(5); // true  
isNumber('q345'); // false
isNumber(null); // false
isNumber(undefined); // false
isNumber(false); // false
isNumber('   '); // false

Solution 3:

The best way I have found is to either check for a method on the string, i.e.:

if (x.substring) {
// do string thing
} else{
// do other thing
}

or if you want to do something with the number check for a number property,

if (x.toFixed) {
// do number thing
} else {
// do other thing
}

This is sort of like "duck typing", it's up to you which way makes the most sense. I don't have enough karma to comment, but typeof fails for boxed strings and numbers, i.e.:

alert(typeof new String('Hello World'));
alert(typeof new Number(5));

will alert "object".

Solution 4:

You're looking for isNaN():

console.log(!isNaN(123));
console.log(!isNaN(-1.23));
console.log(!isNaN(5-2));
console.log(!isNaN(0));
console.log(!isNaN("0"));
console.log(!isNaN("2"));
console.log(!isNaN("Hello"));
console.log(!isNaN("2005/12/12"));

See JavaScript isNaN() Function at MDN.

Solution 5:

Since ES2015 the correct way to check if a variable holds a valid number is Number.isFinite(value)

Examples:

Number.isFinite(Infinity)   // false
Number.isFinite(NaN)        // false
Number.isFinite(-Infinity)  // false

Number.isFinite(0)          // true
Number.isFinite(2e64)       // true

Number.isFinite('0')        // false
Number.isFinite(null)       // false