Skip to content

All topics  /  JavaScript

How to Check if a Variable is a Number in Javascript?

JavaScript ·

When “How to Check if a Variable is a Number in Javascript?” moves through design, development and browser testing, hiring quota can clarify hand-offs and time spent on revisions while leaving code quality, accessibility and released behaviour as the real measures of success.

For API changes, browser support and current usage patterns, compare the snippet with MDN Web Docs before adopting it in production.

In this tutorial, you will learn check whether variable is number or string in javascript. you can see how to check if a variable is a number in javascript. I would like to share with you check whether variable is number or string in javascript. I explained simply step by step 3 ways to check if variable is a number in javascript. you will do the following things for how to check whether a var is string or number using javascript.

There are several ways to check if a variable is a number in JavaScript:

Example 1: Using the typeof operator


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>How to Check if a Variable is a Number in Javascript? - NiceSnippets.Com</title>
</head>
<body>
</body>
<script type="text/javascript">
    let num = 123;
    if (typeof num === 'number') {
      console.log('num is a number');
    }
</script>
</html>

Example 2: Using the isNaN() function

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>How to Check if a Variable is a Number in Javascript? - NiceSnippets.Com</title>
</head>
<body>
</body>
<script type="text/javascript">
    let num = 'abc';
    if (!isNaN(num)) {
      console.log('num is a number');
    }
</script>
</html>

Example 3: Using regular expressions

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>How to Check if a Variable is a Number in Javascript? - NiceSnippets.Com</title>
</head>
<body>
</body>
<script type="text/javascript">
    let num = '123';
    if (/^\d+$/.test(num)) {
      console.log('num is a number');
    }
</script>
</html>

Example 4: Using the Number() function

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>How to Check if a Variable is a Number in Javascript? - NiceSnippets.Com</title>
</head>
<body>
</body>
<script type="text/javascript">
    let num = '123';
    if (!isNaN(Number(num))) {
      console.log('num is a number');
    }
</script>
</html>