How to write isNumber() in JavaScript?
Tutorial on how to code a isNumber() function to check if a value is a number or not 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
Related Posts
How to Check null Values in JavaScript? | isNull() JavaScript
Find out how to check if object values is null in JavaScript using isNull() function.
Generate Random Number in a specific range in JavaScript
This post is about how to generate random number in a given range in JavaScript.
Fix error:0308010C:digital envelope routines::unsupported
Learn to solve the "Error: error:0308010C:digital envelope routines::unsupported" error in Node.js application (Vue, Angular or react) using the solutions in this article.
Press Shift + Enter for new Line in Textarea
Override default textarea behavior on Enter key press without Shift, prevent new lines, and take custom actions like submitting forms instead. Still allow Shift+Enter newlines.
