How to check if variable is a number in JavaScript (NaN, typeof, regex)


There are multiple ways to can check if a given variable (var) is a number or not in JavaScript. Let us take a look at a few of them with examples.


Example 1: Using typeof operator

    var variable = 22.5;
    
    if (typeof variable === 'number') {
        console.log('The variable is a number!');
    } else {
        console.log('The variable is not a number!');
    }
    Output:

    The variable is a number!

    Documentation:


    typeof operator returns a string indicating the type of the operand's value.

    Example 1: console.log(typeof 101);

    Output: number

    Example 2: console.log(typeof "Mike");

    Output: string

    Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

Example 2: Using Number.isNaN()


Example 3: Using Regular Expression

    var variable = 100;
    const regexStr = "/^-?\d+(\.\d+)?$/";
    if (regexStr.test(variable)) {
        console.log('The variable is a number.');
    } else {
        console.log('The variable is not a number.');
    }

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap