Check whether a variable is a number in JavaScript

To check whether a variable is a number in JavaScript, you can use any of the following methods. 1) Using isNaN(), 2) Using Number(), 3) Using typeof().

Check whether a variable is a number in JavaScript

In JavaScript, You can use any of the following methods to check if a variable is a number or not.

  1. Using isNaN() function.
  2. Using Number().
  3. Using typeof().

1) Using isNaN()

This function returns true if the variable is not a number.

<!DOCTYPE html>
<html>
<head>
    <title>Learn JavaScript</title>
</head>
<body>
    <script>
        var a=50, b="Hello";
        if(isNaN(a))
        {
            document.write(a + " (a) Is not a number<br>");
        }
        else
        {
              document.write(a + " (a) Is a number<br>");
        }

        if(isNaN(b))
        {
            document.write(b + " (b) Is not a number<br>");
        }
        else
        {
            document.write(b + " (b) Is a number<br>");
        }
    </script>
</body>
</html>

Output

50 (a) Is a number
Hello (b) Is not a number

2) Using Number()

This function returns true if the variable is a number.

<script>
    var a=50, b="Hello";
    if(Number(a)){
        document.write(a + " (a) Is a number<br>");
    }
    else{
        document.write(a + " (a) Is not a number<br>");
    }

    if(Number(b)){
        document.write(b + " (b) Is a number<br>");
    }
    else{
        document.write(b + " (b) Is not a number<br>");
    }
</script>

Output

50 (a) Is a number
Hello (b) Is not a number

3) Using typeof()

The typeof() returns the type of a variable. For a number, it returns number.

<script>
    var a=50, b="Hello";
    if(typeof(a)=="number"){
        document.write(a + " (a) Is a number");
    }
    else{
        document.write(a + " (a) Is not a number");
    }

    if(typeof(b)=="number"){
        document.write(b + " (b) Is a number<br>")
    }
    else{
        document.write(b + " (b) Is not a number<br>")
    }
</script>

Output

50 (a) Is a number
Hello (b) Is not a number


Share Tweet Send
Loading...