Check if variable is a number in JavaScript

To check if a variable is not a number in javascript; Through this tutorial, i am going to show you how to check whether a variable or given value is number or not in javascript.

Check if variable is a number in JavaScript

In JavaScript, there are two ways to check if a variable is a number :

  • isNaN() JavaScript – isNaN Stands for “is Not a Number”, if a variable or given value is not a number, it returns true, otherwise it will return false.
  • typeof JavaScript – If a variable or given value is a number, it will return a string named “number”. In JavaScript, the typeof operator returns the data type of its operand in the form of a string.

1. isNaN JavaScript

Using the JavaScript’s “isNaN” method, you can check if a variable is a number in javascript; as follows:

<!DOCTYPE html>
<html>
<title>Check if variable is a number or not in JavaScript Using isNaN()</title>
<head></head>
<body>
<h1>Check if variable is a number or not in JavaScript Using isNaN()</h1>
<input type="text" id="demo" value="" placeholder="Please enter here.....">
<button onclick="myFunction()">Click & See Result</button>
<script type="text/javascript">
    function myFunction() {
      var num = document.getElementById("demo").value; 
      console.log(num);
       if(isNaN(num)){
        alert(num + " is not a number");
       }else{
         alert(num + " is a number");
       }
  }
</script>
</body>
</html>

2. typeof JavaScript

Using the JavaScript’s “typeof” operator, you can check if a variable is a number in javascript; as follows:

<!DOCTYPE html>
<html>
<title>Check if variable or given value is a number or not in JavaScript Using javascript Typeof</title>
<head></head>
<body>
<h1>Check if variable or given value is a number or not in JavaScript Using javascript Typeof</h1>
<input type="text" id="demo1" value="" placeholder="Please enter here.....">
<button onclick="javascriptTypeof()">Click & See Result</button>
<script type="text/javascript">
    function javascriptTypeof() {
      var num = document.getElementById("demo1").value; 
      if(typeof num == 'number'){
        alert(num + " is a number");
       }else{
        alert(num + " is not a number");
       }
  }
</script>
</body>
</html>

Conclusion

To check if a variable is not a number in javascript; In this tutorial, you have learned easy two ways to check a given value is number or not with example and live demos.

More JavaScript Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *