JavaScript Code


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


Check if all the numbers in array are odd 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 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