You can use several methods to check if a value is a number in JavaScript.
Here are four best ways to check:
The typeof operator returns a string indicating the type of the value. If it returns 'number', then the value is a number.
function isNumber(value) {
return typeof value === 'number';
}
The isNaN() function checks whether a value is NaN (Not-a-Number). By using the negation operator (!), you can determine if the value is a valid number.
function isNumber(value) {
return !isNaN(value);
}
The Number.isFinite() method checks if a value is a finite number. It returns true for finite numbers and false for NaN, Infinity, or -Infinity.
function isNumber(value) {
return Number.isFinite(value);
}
This approach uses a regular expression to check if the value matches the pattern of a number. It allows an optional sign (+/-) at the beginning and supports decimal numbers.
function isNumber(value) {
return /^[+-]?\d+(\.\d+)?$/.test(value);
}
You can choose the method that suits your requirements and the specific context of your code.
Here is another quick guide about formatting dates in JavaScript.