Exercise 20: Check if Number is Even or Odd
Problem Statement
Create functions `isEven(n)` and `isOdd(n)` that check if a number is even or odd.
Example:
- isEven(4) → true
- isOdd(5) → true
Sample Output:
isEven(4) => true isOdd(5) => true isEven(3) => false isOdd(2) => false
Solution
const isEven = (n) => Number.isInteger(Number(n)) && Number(n) % 2 === 0;
const isOdd = (n) => Number.isInteger(Number(n)) && Number(n) % 2 !== 0;Explanation
Overall Goal:
- Number even ya odd hai check karna.
- Modulo operator use karna.
Line 1: isEven function
const isEven = (n) => Number.isInteger(Number(n)) && Number(n) % 2 === 0;- Integer hai aur 2 se divisible hai.
Line 2: isOdd function
const isOdd = (n) => Number.isInteger(Number(n)) && Number(n) % 2 !== 0;- Integer hai aur 2 se divisible nahi.
Real world:
- UI logic: alternate row colors.
- Data processing: even/odd filtering.
- Algorithms: mathematical operations.
Navigation
Previous
Exercise 19
Next
No next exercise