Skip to main content

How to Check if an Array Contains Only Numbers in JavaScript

Validating the contents of an array is a common data sanitization task. Before performing mathematical operations on a list of values, you need to be sure that every element in the array is a number. Depending on your requirements, this could mean checking for strict number types or allowing for numeric strings (like "42").

This guide will teach you the most effective and modern methods for both scenarios. You will learn how to use the Array.prototype.every() method to perform these checks concisely and efficiently, and understand the crucial difference between using typeof and isNaN().

The Core Method: Array.prototype.every()

The every() method is the perfect tool for this job. It tests whether all elements in an array pass a test implemented by a provided function.

  • It iterates through each element of the array.
  • If the callback function returns false for any element, every() immediately stops and returns false.
  • If the callback returns true for all elements, every() returns true.

This "short-circuiting" behavior makes it very efficient, as it doesn't need to check the entire array if it finds an invalid element early on.

Scenario 1: Checking for Strictly number Types

This is the most common and strictest check. It ensures that every element is of the JavaScript number data type. It will reject numeric strings like "123".

Problem: we need to validate an array, but one of them contains a numeric string, which should be considered invalid for this strict check.

// Problem: How to confirm all elements are of the 'number' type?
const strictArray = [1, 2, 3, 4];
const mixedArray = [1, 2, '3', 4]; // Contains a string

Solution: use every() with a typeof check to test each element's data type.

function containsOnlyNumbers(array) {
return array.every(element => typeof element === 'number');
}

// Example Usage:
console.log(containsOnlyNumbers([1, 2, 3, 4])); // Output: true
console.log(containsOnlyNumbers([1, 2, '3', 4])); // Output: false
console.log(containsOnlyNumbers([1, 'hello', 3])); // Output: false

This is the most reliable way to ensure your array contains only true numbers, ready for any mathematical operation.

Scenario 2: Checking for Numeric Values (including strings)

Sometimes, you may want to be more lenient and accept strings that represent numbers (e.g., "123"). This is common when dealing with input from HTML forms, where values are often strings.

Problem: we need a function that will return true for an array of numeric strings.

// Problem: How to validate an array that includes numeric strings?
const numericStringArray = ['10', '20', '30'];
const nonNumericArray = ['10', 'twenty', '30'];

Solution: Use every() with the global !isNaN() function. The isNaN() function determines if a value is "Not-a-Number."

function containsNumericValues(array) {
return array.every(element => {
// !isNaN() returns true if the value IS a number or a numeric string.
return !isNaN(element);
});
}

// Example Usage:
console.log(containsNumericValues([1, 2, 3])); // Output: true
console.log(containsNumericValues(['10', '20', '30'])); // Output: true
console.log(containsNumericValues([10, 'twenty', 30])); // Output: false
note

Important Note: isNaN() can have some quirky behaviors with null (!isNaN(null) is true). For even stricter validation that avoids these quirks, you can combine checks: !isNaN(element) && element !== null. However, for most common cases, !isNaN() is sufficient.

An Alternative: The for...of Loop

While every() is more functional and concise, you can achieve the same result with a traditional for...of loop. This can be more readable for developers who are less familiar with functional programming concepts.

Solution: this function performs the same strict typeof check as in Scenario 1.

function containsOnlyNumbers(array) {
for (const element of array) {
if (typeof element !== 'number') {
return false; // Found a non-number, exit early
}
}
return true; // All elements passed the check
}

// Example Usage:
console.log(containsOnlyNumbers([1, 2, 3])); // Output: true
console.log(containsOnlyNumbers([1, '2', 3])); // Output: false

The return false; inside the loop provides the same efficient "short-circuiting" behavior as every().

Conclusion

Validating that an array contains only numbers is a simple task with every(), but it's crucial to choose the right check for your specific needs.

  • For strict number type checking, use the typeof operator: array.every(el => typeof el === 'number')
  • For a more lenient check that includes numeric strings (like "123"), use the isNaN() function: array.every(el => !isNaN(el))

The every() method is generally the most concise and modern approach, but a for...of loop is a perfectly valid and readable alternative.