JavaScript Code

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


Problem Statement

given an array of numbers, write a JavaScript program to check if all the numbers in the given array are odd numbers

Solution

to check if all the numbers in the given array are odd, call every() method on this array, and pass a function that returns true for an odd number, or false otherwise

Program

numbers is the given array of numbers. isOdd is the function that checks if a given number is odd or not. every() method checks if every element in the numbers array is odd

function isOdd(num) {
    if (num % 2 == 1) {
        return true;
    } else {
        return false;
    }
}

let numbers = [3, 15, 1, 7, 81];
let output = numbers.every(isOdd);
console.log('Are all numbers odd? : ' + output);

you may take some even numbers in the numbers array and check the result



copyright @2022