Categories
JavaScript JavaScript Basics

How to Check if a Variable is a Number

Spread the love

We can check if a variable is a number in multiple ways.

isNaN

We can check by calling isNaN with the variable as the argument. It also detects if a string’s content is a number. For example:

isNaN(1) // false  
isNaN('1') // false  
isNaN('abc') // true

Note: isNaN(null) is true .

typeof Operator

We can use the typeof operator before a variable to check if it’s a number, like so:

typeof 1 == 'number' // true  
typeof '1' == 'number' // false

Leave a Reply

Your email address will not be published. Required fields are marked *