• Post category:JavaScript
  • Reading time:3 mins read

In this short article, we’ll show you how to check whether a variable is a number in JavaScript. Here, you will find the easiest way to check if the value is a number or not.

Ways to check whether a variable is number in JavaScript

  1. isNaN() function
  2. typeof operator

1. isNaN() function

The first one is isNaN(), a global variable that stands for is Not a Number. This function returns false if value is a number.



To check if a variable is a number, we will write condition like below:

var num = 5;
if(!isNaN(num)) {
    console.log(num + " is a number");
// Output: 5 is a number

var str = "codepremix";
if(isNaN(str)) {
    console.log(str + " is not a number");
// Output: codepremix is not a number

2. typeof operator

The typeof operator uses for the check the type of the variable and returns the string. JavaScript has 9 types as below:

  • undefined
  • null
  • boolean
  • number
  • string
  • bigint
  • object
  • symbol
  • function (a special type of object)

Let’s take an example.

var num = 567;
if(typeof num == "number") {
    console.log(num + " is a number");
else {
    console.log(num + " is not a number");
// Output: 567 is a number

That’s it for today.
Thank you for reading. Happy Coding..!!

Leave a Reply