programming.protips.wiki
githubtwitter

Return early from a function when checking initial conditions

When conditionally executing logic in a function based on some initial condition(s), consider returning early.

Guards implement this pattern.

Bad Example

function parseConfigFile(filePath) {
  if (typeof filePath === 'string') {
    const contents = fs.readFileSync(filePath, 'utf8');
    const configJson = JSON.parse(contents);
    const { projectName } = configJson;
    // ...
    // ...
    // ... more function logic
    // ...
    return configJson;
  } else {
    throw new Error('No config file path was supplied');
  }
}

Prefer

function parseConfigFile(filePath) {
  if (!filePath) {
    throw new Error('No config file path was supplied');
  }

  const contents = fs.readFileSync(filePath, 'utf8');
  const configJson = JSON.parse(contents);
  const { projectName } = configJson;
  // ...
  // ...
  // ... more function logic
  // ...
  return configJson;
}

By returning (or throwing!) early, we reduce the level of nesting for the rest of the function, improving readability.

You can write multiple guards (not too many!) at the top of the function when checking inputs.

Note: This doesn't advocate for randomly returning in the middle of a function - which would be somewhat chaotic :)

Further reading: