# 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.

TOP Interview Coding Problems/Challenges

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions

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