Let’s start with the first one.

Imagine that you have a user object and you want to print its name. Such a method might look like this:

const getName = (user) => {
  return `${user.firstName} ${user.lastName}`;
}

We frequently don’t know if both fields contain data, however. In some backwards systems, the first name might be empty and the last name might be a company name.1 To get around this, you might see some verbose logic such as this:

/**
 * Too much codez...
 */
const getName = (user) => {
  let output = '';
  if (user.firstName) {
    output = user.firstName;
  }
  if (user.lastName) {
    if (user.firstName) {
      output += ' ';
    }
    output = user.lastName;
  }

  return output;
}

A niftier way to handle this is to just assume that both fields do contain data and then trim any whitespace. The function below achieves the exact same thing as the one above, albeit more elegantly:

/**
 * Hire this guy!
 */
const getName = (user) => 
  `${user.firstName} ${user.lastName}`.trim();

Now for the second tip.

Let’s say you’re generating timestamps, such as:

  • 8:04 AM
  • 5:23 PM
  • etc

When you’re piecing this together from a JavaScript Date object, you use something like the Date.getMinutes() property. Often you’ll see code that looks something like this:

/**
 * Whaaa
 */
const getMinutes = (date) => {
  const minutes = date.getMinutes();
  let output = minutes;
  if (minutes < 10) {
      output = `0${output}`;
  }
  return output;
}

The code is trying to make sure that there are always two digits for the seconds. There’s a groovier way to do this though:

/**
 * Lit!
 */
const getMinutes(date) => 
  `0${date.getMinutes()}`.substr(-2);

Lastly the third tip.

Often you see code that looks something like this:

/**
 * We do this all the time, sigh
 */
if (user.location === 'Chicago' || 
  user.location === 'New York' ||
  user.location === 'San Francisco') {
  doTheThing();
}

Here’s a cleaner way:

/**
 * Array literals for the win
 */
if (['Chicago', 'New York', 'San Francisco']
  .indexOf(user.location) >= 0) {
  doTheThing();
}

These tips have use cases outside these particular examples and they can easily transfer to other programming languages.


  1. This sort of blasphemy occurs when you have a lazy database designer who, in their infinite wisdom, chooses to use a single cell-starved table for both personal accounts and business accounts. Such design is pure evil and ought never to be imagined. ↩︎