How to Use the isNaN() Function in JavaScript

Contents
In this article, you will learn how to use the isNaN() function in JavaScript.
Using the isNaN() Function in JavaScript
The isNaN() function is a built-in function in JavaScript that checks whether a value is NaN (Not a Number). It returns true if the value is NaN and false otherwise. The isNaN() function can be useful in various scenarios such as input validation, numeric calculations, and comparisons.
Syntax
The syntax for the isNaN() function is as follows:
isNaN(value)
Parameters
The isNaN() function takes only one parameter, which is the value to be checked. The value can be of any data type, but it is usually a number or a string that represents a number.
Return value
The isNaN() function returns a Boolean value, true or false. If the value is NaN, it returns true. Otherwise, it returns false.
Examples
Let’s look at some examples to understand how to use the isNaN() function in JavaScript.
Check if a value is NaN
let x = "Hello";
console.log(isNaN(x)); // Output: true
let y = 123;
console.log(isNaN(y)); // Output: false
In the above example, we have declared two variables x and y. The value of x is a string “Hello”, which is not a number, so the isNaN() function returns true. The value of y is a number, so the isNaN() function returns false.
Use isNaN() function in an if statement
let z = "ABC";
if (isNaN(z)) {
console.log("The value is not a number");
} else {
console.log("The value is a number");
}
In the above example, we have used the isNaN() function in an if statement to check whether the value of z is a number or not. Since z is not a number, the if condition is true, and the output is “The value is not a number”.