JavaScript Code

How to check if all the numbers in array are even?


Problem Statement

given an array of numbers, 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, 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



copyright @2022