DEV Community

loading...

JavaScript Is Number Check If Variable Is A Number In JavaScript

skptricks
Welcome to skptricks, I have written and developed this site so that Learner may learn computer science related technologies and various programming ...
・1 min read

Post Link : Check If Variable Is A Number In JavaScript

This tutorial explains how to check variable is a number in javascript. Lets see the below example, where we have used typeof operator and isNaN() function to verify the variable is number or not.
typeof – If variable is a number, it will returns a string named "number".
isNaN() – Stands for "is Not a Number", if variable is not a number, it return true, else return false.

Using typeof operator :
In this example, we have used typeof operator, and verifying the variable is number or not in javscript.
// In this variable we are storing number...
var num1 = 758;

// verifying by using typeof operator
if(typeof num1 == 'number'){
console.log(num1 + " is a number.");
}else{
console.log(num1 + " is not a number.");
}

Output :

"758 is a number."

Discussion (1)

Collapse
grok profile image
Sterling Hamilton

Hey there skptricks!

I stumbled upon this while writing my own and wanted to point out something.

You cannot rely on isNaN() for checking if something is a number. You can use it to check if the input provided to isNaN() will cause further NaN values. If that makes sense.

Using it the way you have, true and false will result in true is a number.

Here's a function I wrote to check if something is a number: codepen.io/grok/pen/LvOQbW?editors...