Technology3 min read

Check if a Variable is a number or not in JavaScript

Abhishek Ahlawat

By Abhishek Ahlawat โ€” Recently

Founder of StudyTonight and a MERN fullstack developer. Writes about JavaScript, web development, Linux, and tech.

Summarize this article using AI

In JavaScript, you can check if a variable is a number or not using one of the following two ways:

  1. Using isNaN() function

  2. Using typeof operator

Let's see both the approach with code examples.




Using isNaN() function

isNaN stands for "is Not a Number". This function takes one argument and returns True if the argument provided is not a number, and returns False if a numeric value is passed as argument to this function. Following is the syntax for this function:

isNaN(variable)

where, variable is the name of a variable which may or may not have a number value.

Let's take an example,

var num = 1;
var str = "Studytonight";

if(isNaN(str)) {
    console.log(str + " is not a number");
}

if(!isNaN(num)) {
    console.log(num + " is a number");
}

Output:

Studytonight is not a number
1 is a number

Note: In the second if condition, we have used the not ! operator with isNaN() function, to check if the variable passed is a number.




Using typeof Operator

The typeof operator can be used to see the type of a variable. For example, if we use the typeof operator with a string value, it will return string and if we use the typeof operator with a numeric value, it will return number as result.

var num = 1;

if(typeof num == "number") {
    console.log(str + " is not a number");
}
else {
    console.log(num + " is a number");
}

Output:

1 is a number



Time for an Example

Below, we have a running code example, where we have used both isNaN() function and typeof operator. Try running the code with different values for num and str variables.

Use the Run button to run the code.


SHARE YOUR THOUGHTS WITH US!


Spotted something outdated or wrong?

Liked this? See more StudyTonight posts in Google results.

Add StudyTonight as a preferred source
Next questLIVE OPSStep 2 / 3

Practice real incidents in the browser

System Design Ops โ€” put out fires, ship fixes, and stack XP. Reading done. Time to play.

Play System Design
  • +XP

    Every sim

  • Incidents

    Live ops

  • Ranks

    Climb up

Read next