To check if a number is even or odd in JavaScript, you can use the following approach:
1. First, define a function that takes an argument num. This argument will be the number that you want to check.
function checkEvenOdd(num) {
// code to check if num is even or odd
}
2. Inside the function, you can use the modulo operator (%) to check if the number is divisible by 2. If the number is divisible by 2, it is even. Otherwise, it is odd.
function checkEvenOdd(num) {
if (num % 2 == 0) {
console.log(num + " is even");
} else {
console.log(num + " is odd");
}
}
3. To test the function, you can call it with different numbers as arguments.
checkEvenOdd(2); // Output: 2 is even
checkEvenOdd(3); // Output: 3 is odd
checkEvenOdd(4); // Output: 4 is even
Here is the complete code:
function checkEvenOdd(num) {
if (num % 2 == 0) {
console.log(num + " is even");
} else {
console.log(num + " is odd");
}
}
checkEvenOdd(2); // Output: 2 is even
checkEvenOdd(3); // Output: 3 is odd
checkEvenOdd(4); // Output: 4 is even
Comments (0)