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

27-Jun-2023

.

Admin

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

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>

#JavaScript