I am currently available for freelance/contract work. Book a meeting so we can talk about your project.

Extracting complex logic to named functions

Posted on

If a piece of code looks cryptic and is difficult to understand, we can put it in a separate function. The descriptive name we’re giving to that function helps explain what it does.

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"
// 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"
Debug
none
Grid overlay