Clue Mediator

Check if a variable is a number in JavaScript

📅November 20, 2020

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

Ways to check if a variable is a 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.

Syntax:

isNaN(variable)

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 = "cluemediator";
if(isNaN(str)) {
    console.log(str + " is not a number");
}

// Output: cluemediator 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..!!