Don’t Document the Obvious

In Chapter 8, “Functions and Methods,” you learned about DRY code. The “don’t repeat yourself” concept extends to comments as well. Documentation that restates exactly what is happening in the code adds no value. Instead, it gets in the way by breaking up the flow of the code, and it gets outdated too quickly. Listing 10.5 contains the same code as in Listing 10.2, but Listing 10.5 is written with comments describing every line. Which is easier to read?

Listing 10.5 Repeating Your Code in the Form of Comments Is Not Helpful

/** * Get location */function getLocation(phoneNumber) {  // Create the phone number pattern  var phoneNumberPattern = /(?:1-)?\(?(\d{3})[\-\)]\d{3}-\d{4}/;  // Get ...

Get Learning to Program now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.