4.11 Exercise: Landscape or Portrait
Here is another exercise: implement a function called isLandscape that takes two parameters — the width and the height of an image — and returns true when the image is in landscape format (width greater than height) and false otherwise. Pause the video and try it on your own before reading the correction.
From if / else to a clean expression
A straightforward implementation uses an if / else, but we can do much better:
// Naive — returns true/false explicitly
function isLandscape(width, height) {
if (width > height) return true;
else return false;
}
// Slightly better with the ternary operator
function isLandscape(width, height) {
return width > height ? true : false;
}
// Best — return the comparison directly
function isLandscape(width, height) {
return width > height;
}
The last version is the cleanest: the comparison width > height already evaluates to a boolean, so wrapping it in a conditional that returns true or false is pure noise.
isLandscape(800, 600)returnstrue.isLandscape(300, 600)returnsfalse.
Avoid the anti-pattern of explicitly returning true or false when the surrounding expression is already a boolean. See you in the next demonstration.
Summary
In this exercise, you learn to implement a landscape() function that determines if an image is in landscape or portrait format by comparing its width and height parameters. The lesson demonstrates how to refactor code by eliminating unnecessary explicit true and false return statements, instead returning the boolean expression directly. You then test the function using console.log() with sample dimensions to verify the results.
Key points
- Implement a function that checks if an image width is greater than its height
- Use simple if-else statements as the first approach to the problem
- Optimize code by returning the boolean expression directly instead of wrapping it in if-else with explicit returns
- Avoid returning true and false explicitly—let the comparison operator return the boolean value
- Test the function with console.log() using concrete image dimensions (e.g., 800×600 for landscape, 300×600 for portrait)
FAQ
Why should we avoid writing if (width > height) return true; else return false;?
Because the expression width > height already evaluates to a boolean (true or false). Wrapping it in an if-else that explicitly returns true or false is redundant and makes the code less readable. Instead, you can directly return the boolean expression.
How do you test if the landscape function works correctly?
Use console.log() to call the function with sample dimensions. For example, landscape(800, 600) should return true (width > height), and landscape(300, 600) should return false (width < height).
What is the difference between landscape and portrait orientation?
Landscape orientation means the image width is greater than its height, while portrait orientation means the height is greater than the width.