Extracting complex logic to named functions

If a piece of code looks cryptic and is difficult to understand, put it in a function. By giving that function a descriptive name, your code becomes much more readable. A good name can make a long comment unnecessary.

// We can get today’s date in a specific timezone with `.toLocaleString()`.
// The code looks complicated, and we might not remember what it does two
// months from now.

const now = new Date()
const nowAsString = now.toLocaleString('en-US', {
  timeZone: 'America/Los_Angeles'
})
nowAsString.match(/\d{1,2}\/\d{1,2}\/\d{4}/)[0]
// ⇒ '8/15/2020'

// Putting this code into a function makes it easily reusable. We don’t need
// to write a comment for it because the name already explains what it does.
// It’s okay to condense the code and skip a few variables in this case.

const getDateInLosAngeles = () => (new Date()).toLocaleString('en-US', {
  timeZone: 'America/Los_Angeles'
}).match(/\d{1,2}\/\d{1,2}\/\d{4}/)[0]

// Getting the date with one function call is more convenient and readable.
getDateInLosAngeles()
// ⇒ '8/15/2020'

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.