Check if all the numbers in array are even in JavaScript
In this tutorial, you are given an array of numbers. You should write a JavaScript program to check if all the numbers in the given array are even numbers.
Solution
To check if all the numbers in the given array are even in JavaScript, call every() method on this array, and pass a function that returns true for an even number, or false otherwise.
Program
numbers
is the given array of numbers. isEven
is the function that checks if a given number is even or not. every()
method checks if every element in the numbers
array is even.
function isEven(num) {
if (num % 2 == 0) {
return true;
} else {
return false;
}
}
let numbers = [4, 10, 8, 18];
let output = numbers.every(isEven);
console.log('Are all numbers even? : ' + output);
You may take some odd numbers in the numbers
array and check the result.