How to write isNumber() in JavaScript?


In this short article we will see how to write isNumber() in JavaScript.

We can code a IsNumber() function in JavaScript which will check if a value is a number or not. If the given value is a number it will return true , if it's not it will return false.

Using Vanilla JavaScript

Code :

function isNumber(value){
  return typeof value === 'number' && isFinite(value);
}

console.log(isNumber(22)) //true
console.log(isNumber('2')) // false
console.log(isNumber('hello')) //false

Code Explanation:

The isNumber(vlaue)function take a value as an argument from the user.

typeof : The typeof is a JavaScript operator to find the data type of the variable. The code typeof value === 'number' will return true if the type of the value is a number.

isFinite(value) : The isFinite() is a function that checks whether a number is a finite number. It will return false if the given value is positive or negative infinity, undefined or NaN (Not a Number), otherwise if its a number it will return true.

Using underscoreJs or Lodash

In underscorejs or Lodash JavaScript Library, we can check if a value is a number by using the _.isNumber() function.

Syntax:

_.isNumber( object )

It will check if the given object argument is a number or not. If the given value is a number it will return true otherwise it will return false.

Related Topics:

Check If String Is A Number Or Not In JavaScript

Check If A String Contains A Substring In Javascript

How To Stop And Exit A Function In JavaScript?

How To Check Null Values In JavaScript?


💾 Recommended Articles