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) returns true.
  • isLandscape(300, 600) returns false.

Avoid the anti-pattern of explicitly returning true or false when the surrounding expression is already a boolean. See you in the next demonstration.