Anjan Dutta

How to check if a value is a number in javascript

How to check if a value is a number in javascript

We can use isNaN() and typeOf() functions to check if a variable is number or not in javascript.

Check using isNaN() function.

var x = 8;
if (isNaN(x)) {
console.log('Not a number!');
} else {
console.log('It's a number!');
}

In the above code example, the if condition checks if the variable is a number or not.

isNaN(x) this statement will return true if the variable x is not a number. And, false if the variable is a number.

Check using typeof function.

const value = 2
typeof value; // number

The typeof identifier returns the data type of any given variable or constant.

To test a variable is a number or not, we can put a check directly on its type like below.

var x = 8;
if (typeof x === "number") {
console.log('It's a number!');
} else {
console.log('Not a number!');
}

type of number