Last updated: Mar 2, 2024
Reading timeยท3 min

To check if an array contains only numbers:
Array.every() method to iterate over the array.number.every() method will return true if the array contains only numbers
and false otherwise.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.
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.
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.
console.log(isNaN('test')); // ๐๏ธ true console.log(isNaN('1')); // ๐๏ธ false
An easy way to think about it is:
isNaN() (is Not a Number) function tries to convert the passed-in
element to a number and returns true if it can't.! operator, to check if all
elements in the array can be converted to numbers.You can also use a for...of loop to check if an array contains only numbers.
for...of loopThis is a three-step process:
for...of loop to iterate over the array.number.false and exit the loop.function onlyNumbers(array) { let containsOnlyNumbers = true; for (const element of array) { if (typeof element !== 'number') { containsOnlyNumbers = false; break; } } return containsOnlyNumbers; } const arr1 = [1, 2, 3]; const arr2 = [1, 2, 'three']; const arr3 = ['1', '2', '3']; console.log(onlyNumbers(arr1)); // ๐๏ธ true console.log(onlyNumbers(arr2)); // ๐๏ธ false console.log(onlyNumbers(arr3)); // ๐๏ธ false

The for...of statement is
used to loop over iterable objects like arrays, strings, Map, Set and
NodeList objects and generators.
On each iteration, we check if the current element doesn't have a type of
number.
If the condition is met, we set the containsOnlyNumbers boolean to false and
use the break statement to exit the for...of loop.
The onlyNumbers() function takes an array and returns true if the array
contains only numbers and false otherwise.
You can learn more about the related topics by checking out the following tutorials: