Check if Array contains only Numbers in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 16 20212 min read

banner

Photo by Motoki Tonn

Check if Array contains only Numbers #

To check if an array contains only numbers:

  1. Call the every() method, passing it a function.
  2. On each iteration, check if the type of of the current element is number.
  3. The every method returns true, only if the condition is met for every array element.
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 pass 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 and returns false.

On each iteration we return whether the element has a type of number. 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 use 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 using the logical NOT ! operator, to check if all elements in the array can be converted to numbers.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee