How to write isNumber() in JavaScript?

featured Image

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

How To Stop And Exit A Function In JavaScript?

How To Check Null Values In JavaScript?

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more