JavaScript
// Method 1: Using if-else
let number = 7;
if (number % 2 === 0) {
console.log(number + " is even");
} else {
console.log(number + " is odd");
}
// Method 2: Using ternary operator
let num = 8;
let result = (num % 2 === 0) ? "even" : "odd";
console.log(num + " is " + result);
// Method 3: Using function
function checkEvenOdd(n) {
if (n % 2 === 0) {
return "even";
} else {
return "odd";
}
}
console.log("10 is " + checkEvenOdd(10));
console.log("15 is " + checkEvenOdd(15));Output
7 is odd 8 is even 10 is even 15 is odd
This program demonstrates conditional logic using the modulus operator.
Modulus Operator (%)
The modulus operator returns the remainder after division:
number % 2 === 0→ Even numbernumber % 2 === 1→ Odd number
If-Else Statement
Basic conditional structure:
javascriptif (condition) { // code if true } else { // code if false }
Ternary Operator
Shorthand for if-else:
javascriptcondition ? valueIfTrue : valueIfFalse
Comparison Operators
===: Strict equality (checks value and type)!==: Strict inequality==: Loose equality (avoid, can cause bugs)!=: Loose inequality (avoid)
Best Practice: Always use === for equality checks!
Function Approach
Creating reusable function:
javascriptfunction checkEvenOdd(n) { return (n % 2 === 0) ? "even" : "odd"; }
Edge Cases
javascriptcheckEvenOdd(0); // "even" checkEvenOdd(-2); // "even" checkEvenOdd(-3); // "odd"