W3jar
321 words
2 minutes

# How to Check if a Value is a Number in JavaScript

2024-07-28

In JavaScript, there are several methods to check if a value is a number. Here’s a summary of the most common techniques:

### 1. Using typeof#

The typeof operator returns a string indicating the type of the operand. For checking if a value is a number:

function isNumber(value) {
return typeof value === "number";
}

// Examples
console.log(isNumber(42)); // true
console.log(isNumber("42")); // false
console.log(isNumber(NaN)); // true
console.log(isNumber(Infinity)); // true

### 2. Using Number.isFinite()#

This method checks if a value is a finite number (i.e., not NaN, Infinity, or -Infinity).

function isFiniteNumber(value) {
return Number.isFinite(value);
}

// Examples
console.log(isFiniteNumber(42)); // true
console.log(isFiniteNumber(NaN)); // false
console.log(isFiniteNumber(Infinity)); // false
console.log(isFiniteNumber("42")); // false

### 3. Using Number.isNaN()#

To specifically check if a value is NaN, you can use this method:

function isNaNValue(value) {
return Number.isNaN(value);
}

// Examples
console.log(isNaNValue(NaN)); // true
console.log(isNaNValue(42)); // false
console.log(isNaNValue("42")); // false

### 4. Using !isNaN() with parseFloat()#

The isNaN() function determines whether a value is NaN or not. However, it can be tricky because isNaN() will coerce the value to a number first, so using parseFloat() or parseInt() helps ensure the value is actually a number.

function isNumber(value) {
return !isNaN(parseFloat(value)) && isFinite(value);
}

// Examples
console.log(isNumber(42)); // true
console.log(isNumber("42")); // true
console.log(isNumber("42abc")); // false
console.log(isNumber(NaN)); // false

### 5. Using Regular Expressions#

For stricter validation, you can use regular expressions to check if the value represents a valid number:

function isNumber(value) {
return /^-?\d+(\.\d+)?\$/.test(value);
}

// Examples
console.log(isNumber(42)); // false (since 42 is a number, not a string)
console.log(isNumber("42")); // true
console.log(isNumber("42.42")); // true
console.log(isNumber("42abc")); // false

### Conclusion#

• Use typeof value === 'number' to check if a value is a number but be aware that this will include NaN and Infinity.
• Use Number.isFinite(value) for checking if a value is a finite number.
• Use Number.isNaN(value) specifically to check for NaN.
• Use !isNaN(parseFloat(value)) && isFinite(value) for more robust checks, especially when dealing with values that could be strings.
• Use regular expressions for strict validation, mainly when dealing with strings.

Choose the method that best fits your needs based on what types of values you expect to handle.