Check if Array contains only Numbers in JavaScript

avatar

Borislav Hadzhiev

Last updated: Aug 25, 2022

banner

Photo from Unsplash

Check if Array contains only Numbers #

To check if an array contains only numbers:

  1. Use the Array.every() method to iterate over the array.
  2. On each iteration, check if the type of the current element is number.
  3. The every method will return true if the array contains only numbers and false otherwise.
index.js
const arr1 = [1, 2, 3]; const arr2 = [1, 2, 'three']; const arr3 = ['1', '2', '3']; function onlyNumbers(array) { return array.every(element => { return typeof element === 'number'; }); } console.log(onlyNumbers(arr1)); // 👉️ true console.log(onlyNumbers(arr2)); // 👉️ false console.log(onlyNumbers(arr3)); // 👉️ false

The function we passed to the Array.every method gets called with each element in the array until it returns a falsy value or iterates over the entire array.

If the function returns a falsy value, the every method short-circuits returning false.

On each iteration, we check if the element has a type of number and return the result.

The condition has to be satisfied for all array elements for the every method to return true.

If your array contains numbers that might be of type string, use the following approach instead.

index.js
const arr1 = [1, 2, 3]; const arr2 = [1, 2, 'three']; const arr3 = ['1', '2', '3']; function onlyNumbers(array) { return array.every(element => { return !isNaN(element); }); } console.log(onlyNumbers(arr1)); // 👉️ true console.log(onlyNumbers(arr2)); // 👉️ false console.log(onlyNumbers(arr3)); // 👉️ true

We used the isNaN function to determine if the passed in value can be converted to a number or not.

index.js
console.log(isNaN('test')); // 👉️ true console.log(isNaN('1')); // 👉️ false

An easy way to think about it is:

  1. The isNaN (is Not a Number) function tries to convert the passed in array element to a number and returns true if it can't.
  2. We negate the result by using the logical NOT ! operator, to check if all elements in the array can be converted to numbers.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.