Check if the array contains only numbers in JavaScript

Sometimes we may need to check if our array contains only numbers.

We can do this with loops, but there is a bit more elegant solution that uses every():

<script>
  array.every(function (value) {
        return !isNaN(value);        
  });
</script>

Example:

Check if the array contains only valid numbers.

<script>
  var array1 = [5, 2, 7, 'hello'];
  var array2 = [15, 5, 44];


  function checkNumbers(array) {
    return array.every(function (value) {
          return !isNaN(value);        
    });
  }

  if(checkNumbers(array1)) {
    console.log('array1 contains only numbers');
  }

  if(checkNumbers(array2)) {
    console.log('array2 contains only numbers');
  }
</script>

Output (console): array2 contains only numbers