To check if a variable is not a number in javascript; In this tutorial, You will learn how to check whether a variable or given value is number or not in javascript
This tutorial will provide a test demo to checking a given value or variable is number or not. So try these examples use it.
javaScript check if 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
Let’s take a new example of JavaScript’s “isNaN
” method.
<!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>
Demo
Check if variable or given value is a number or not in JavaScript Using isNaN()
2. typeof JavaScript
Let’s take a new example of JavaScript’s “typeof
” operator.
<!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>
Demo
Check if variable or given value is a number or not in JavaScript Using javascript Typeof Operator
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.
Recommended JavaScript Tutorials
If you have any questions or thoughts to share, use the comment form below to reach us.