Check if Variable is a Number in JavaScript

In JavaScript, there are two ways to check if a variable is a number :
  1. isNaN() – Stands for “is Not a Number”, if a variable is not a number, it returns true, else return false.
  2. typeof – If a variable is a number, it will return a string named “number”.

Using isNaN() Function

The isNaN() function determines whether a value is an illegal number (Not-a-Number). This function returns true if the value equates to NaN. Otherwise, it returns false.
let num = 50;

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

let str = "javaguides";

if(isNaN(str)){
    console.log(str + " is not a number");
}else{
    console.log(str + " is a number");
}
Output:
50 is a number
javaguides is not a number
For the best learning experience, I highly recommended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example from this guide, and run it by pressing the Enter/Return key.

Using typeof Operator

The typeof operator is a unary operator that returns a string representing the type of a variable.
let num = 50;

if(typeof num == 'number'){
    console.log(num + " is a number");
}else{
    console.log(num + " is not a number");
}
Output:
50 is a number

Complete Example with Output



Comments