Home » JavaScript

Check if number is a valid number in JavaScript

In this article we will see methods to check if number is a valid number in JavaScript.
Submitted by Abhishek Pathak, on October 19, 2017

Numbers are building blocks of any machine. They are the one of the basic units that languages operate with and manipulate numbers and data to produce output. While working with numbers in JavaScript, it is quite likely that you have come through a situation where a number is not actually a number and we are performing operations on it.

Consider this situation,

Code

var input = prompt('Enter a number');
var output = (0 / input) + 10;

In this code, suppose the user enters 0 in the input. And the output variable will evaluate the expression and store it in output variable. In this situation, 0/0 is not defined and performing addition with it might not produce correct output.

But, JavaScript's isNaN() function is there to save you from these situations. JavaScript has a special data type called, NaN, which simply means Not a number. It is used to represent data that is not a number. Such as square root of -1, 0/0 etc. And to check those NaN values, the isNaN() function expects the data as parameter and returns true if it is Not a Number.

Here, is same program with isNaN() function,

var input = prompt('Enter a number');
var output = 0 / input;

if(isNaN(output))
	console.log('You entered a wrong number');
else
	output = output + 10;

This will store the 0/input in output variable and then check with if condition that the output is not a number. If the operation on output is not a valid number, then isNaN() will return true. Otherwise continue the output operation.

If you like this article, please share your thoughts in the comments below.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.