Check if Variable Is a Number in Javascript

Dec 24, 2022

1 min read

Published in

In Javascript, there are three ways to check if the variable is a number.

  1. Using typeof operator
  2. isNan ( ) function
  3. parseFloat ( ) or parseInt ( ) functions

1. Using typeof Operator

In JavaScript, you can check if a variable is a number by using the typeof operator. The typeof operator returns a text indicating the variable type, and for numbers, it returns “number”. Here’s an example of how user can use the typeof operator to verify if a variable is a number:

1
2
3
4
5
6
let x = 5;
if (typeof x === "number") {
    console.log("x is a number");
} else {
    console.log("x is not a number");
}

2. isNan ( ) function

Another approach is to use the isNaN( ) function, which returns true if the variable is not a number and false if it is a number.

1
2
3
4
5
6
7
let x = "five";

if (isNaN(x)) {
    console.log("x is not a number");
} else {
    console.log("x is a number");
}

3. parseFloat ( ) or parseInt ( ) functions

You can also use the parseFloat() or parseInt() function and compare the variable to the returned value, if it returns NaN, then it is not a number.

1
2
3
4
5
6
7
let x = "5";

if (parseFloat(x) == x) {
    console.log("x is a number");
} else {
    console.log("x is not a number");
}

Users can use any of these three ways depending on the context of your code and what you are trying to accomplish.

Sharing is caring!