4.12 Exercise: Even and Odd Numbers
Here is an exercise: write a function showNumbers that takes a limit parameter and prints every integer from 0 up to the limit, labelling each one as either EVEN or ODD. For example, showNumbers(10) should print 0 EVEN, 1 ODD, 2 EVEN, and so on. Pause the video, give it a try, then read the correction.
A first solution with two console.log
function showNumbers(limit) {
for (let i = 0; i <= limit; i++) {
if (i % 2 === 0) console.log(i, 'EVEN');
else console.log(i, 'ODD');
}
}
The for loop walks the range from 0 to limit included. The if uses the modulo operator %: if the remainder of i / 2 is 0, the number is even; otherwise it is odd.
A cleaner refactor
The duplication of two console.log calls can be removed by building the label first and logging once:
function showNumbers(limit) {
for (let i = 0; i <= limit; i++) {
const message = i % 2 === 0 ? 'EVEN' : 'ODD';
console.log(i, message);
}
}
- The ternary chooses the label in a single expression.
- The single
console.logmakes the loop body easier to read.
Both versions print the same output. See you in the next demonstration.
Summary
This exercise teaches you to write a function that iterates from 0 to a given limit and classifies each number as even or odd using the modulo operator. The lesson demonstrates two implementation approaches: a straightforward if/else method and a cleaner ternary operator technique that reduces code duplication.
Key points
- Use a for loop to iterate from 0 to the specified limit parameter
- Apply the modulo operator (%) with 2 to determine even/odd status: if num % 2 === 0, the number is even
- First approach: use if/else blocks with separate console.log statements for even and odd cases
- Second approach: use the conditional (ternary) operator to assign a message variable before logging, reducing code repetition
- The ternary implementation is cleaner and more maintainable, consolidating logic into a single console.log call
FAQ
How do you check if a number is even or odd in JavaScript?
Use the modulo operator (%) with 2. If the expression num % 2 === 0 evaluates to true, the number is even; otherwise, it is odd.
What advantage does the ternary operator approach provide over the if/else method?
The ternary operator reduces code duplication by consolidating the conditional logic and message definition, resulting in a single console.log statement instead of separate ones for each case.
What parameters does the display function require?
The function takes a single parameter called 'limit', which represents the upper bound for the number range (inclusive) that the function will iterate through and evaluate.