## Check If An Array Contains Only Numbers In JavaScript

To check if an array contains only numbers in JavaScript, use the every() method. This method checks if all the elements in an array pass a test provided as a callback function. For our purposes, we can use the typeof operator as the callback function to check if an element is a number. If all elements pass the test, then every() will return true.

Contents

## Check If An Array Contains Only Numbers In JavaScript

Here’s an example:

``````var arr = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4];

function isNumber(element) {

return typeof element === ‘number’;

}

console.log(arr.every(isNumber)); // true``````

If even one element in the array does not pass the test, every() will return false.

For example:

``````var arr = [-5, -4, -3, -2, -1, 0, 1, 2, 3, ‘4’];

function isNumber(element) {

return typeof element === ‘number’;

}

console.log(arr.every(isNumber)); // false``````

In the above example, the last element in the array is a string, so the test returns false.

If you want such arrays to return true in case there is a String that can be converted to a number, use the NaN check:

``````var arr = [-5, -4, -3, -2, -1, 0, 1, 2, 3, ‘4’];

function isNumber(element) {

return !isNaN(element);

}

console.log(arr.every(isNumber)); // true``````

The isNaN method checks if a value cannot be converted to a number. If the value can be converted to a number, isNaN will return false. So we use a ! operator to negate the result and get true.

You can also use a regular expression as the callback function:

``````var arr = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4];

function isNumber(element) {

return /\d/.test(element);

}

console.log(arr.every(isNumber)); // true``````

The \d is a regular expression that matches any digit character, so this test will return true if all elements in the array are digits.

Finally, here’s a shorter way to write the isNumber function using an arrow function:

``````var arr = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4];

var isNumber = element => /\d/.test(element);

console.log(arr.every(isNumber)); // true``````

## Conclusion

In this article, we saw how to check if an array contains only numbers in JavaScript using the every() method. We also looked at several ways to write the isNumber callback function, including using arrow functions.