Introduction
In this lab, we will explore a JavaScript function that checks whether a given value is a number. We will use the parseFloat() method to convert the value to a number and then validate it using Number.isNaN() and Number.isFinite(). We will also use coercion to check if the value is a number. By the end of this lab, you will have a better understanding of how to validate numbers in JavaScript.
Number Validation Function
To validate if a given input is a number, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
parseFloat()to try to convert the input to a number. - Use
Number.isNaN()and logical not (!) operator to check if the input is a number. - Use
Number.isFinite()to check if the input is finite. - Use
Numberand the loose equality operator (==) to check if the coercion holds.
Here's the code for the validateNumber function:
const validateNumber = (input) => {
const num = parseFloat(input);
return !Number.isNaN(num) && Number.isFinite(num) && Number(input) == input;
};
You can use the validateNumber function as follows:
validateNumber("10"); // true
validateNumber("a"); // false
Summary
Congratulations! You have completed the Validate Number lab. You can practice more labs in LabEx to improve your skills.