In JavaScript, there are multiple ways to check if a variable value is a number. Let’s explore two common approaches.
Method 1: Using isNaN() Function
JavaScript provides a global function called isNaN()
that can be used to check if a value is a number. This function is assigned to the window
object in the browser environment. Here’s an example:
const value = 2;
isNaN(value); // returns false
isNaN('test'); // returns true
isNaN({}); // returns true
isNaN(1.2); // returns false
If the isNaN()
function returns false, it means the value is a number.
Method 2: Using the typeof Operator
Another way to check if a value is a number in JavaScript is by using the typeof
operator. When used on a number value, the typeof
operator returns the string 'number'
. Here’s an example:
typeof 1; // returns 'number'
const value = 2;
typeof value; // returns 'number'
You can use this approach for conditional checks, like so:
const value = 2;
if (typeof value === 'number') {
// it's a number
}
By applying these methods, you can easily determine if a value is a number in JavaScript.
Tags: JavaScript, Number Checking