How to check if a value is a number in JavaScript

How to determine whether the variable value is a number?

We have multiple ways to check whether the value is a number.

first of allisNaN(), Is assigned towindowObjects in the browser:

const value = 2

isNaN(value) //false isNaN(‘test’) //true isNaN({}) //true isNaN(1.2) //false

in caseisNaN()Return false, the valueYesA number.

Another way is to usetypeofoperator. It returns'number'String (if you use it on numeric values):

typeof 1 //'number'

const value = 2

typeof value //‘number’

Therefore, you can perform condition checks like this:

const value = 2
if (typeof value === 'number') {
  //it's a number
}

Download mine for freeJavaScript beginner's manual


More js tutorials: