Check for illegal number with isNaN() in JavaScript

In JavaScript, isNaN() function checks if a value is "Not a Number" (NaN). It's commonly used to validate numeric operations and detect illegal numbers in calculations.

What is NaN?

NaN stands for "Not a Number" and is returned when a mathematical operation fails or produces an undefined result, such as multiplying a string with a number.

Syntax

isNaN(value)

Parameters

value: The value to be tested. If not a number, JavaScript attempts to convert it before testing.

Return Value

Returns true if the value is NaN, false otherwise.

Example: Detecting Illegal Numbers in Calculations

function multiplication(firstValue, secondValue, callback) {
    var res = firstValue * secondValue;
    var err = isNaN(res) ? 'Something is wrong in input parameter' : undefined;
    callback(res, err);
}

multiplication(10, 50, function (result, error) {
    console.log("The multiplication result=" + result);
    if (error) {
        console.log(error);
    }
});

multiplication('Sam', 5, function (result, error) {
    console.log("The multiplication result=" + result);
    if (error) {
        console.log(error);
    }
});
The multiplication result=500
The multiplication result=NaN
Something is wrong in input parameter

Basic isNaN() Examples

console.log(isNaN(123));        // false - valid number
console.log(isNaN('123'));      // false - string converts to number
console.log(isNaN('Hello'));    // true - cannot convert to number
console.log(isNaN(NaN));        // true - explicitly NaN
console.log(isNaN(undefined));  // true - undefined becomes NaN
false
false
true
true
true

Comparison: isNaN() vs Number.isNaN()

Method Type Conversion Strict Check
isNaN() Yes - converts values first No
Number.isNaN() No - checks exact value Yes
console.log(isNaN('Hello'));         // true (converts, then checks)
console.log(Number.isNaN('Hello'));  // false (no conversion)
console.log(Number.isNaN(NaN));      // true (exact match)
true
false
true

Common Use Cases

Form Validation: Check if user input is a valid number before processing.

Mathematical Operations: Validate results of calculations to prevent errors in further computations.

Conclusion

Use isNaN() to detect invalid numeric results in calculations. For strict NaN checking without type conversion, prefer Number.isNaN().

Updated on: 2026-03-15T23:18:59+05:30

251 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements