Skip to content

Instantly share code, notes, and snippets.

@nilz3ro
Last active November 21, 2016 16:34
Show Gist options
  • Save nilz3ro/4f56c85601313a35762fb08250e40d3b to your computer and use it in GitHub Desktop.
Save nilz3ro/4f56c85601313a35762fb08250e40d3b to your computer and use it in GitHub Desktop.
Intro to guard clauses.

Guard Clause

What is it?

A guard clause is a line of code that prevents the following block of code from running unless a certain condition is met.

Why use guard clauses?

Guard clauses are preferrable to nested conditionals because they are faster and simpler than nesting conditional statements.

Links

Example

const obj = {
  a: {
    b: 'value of b!'
  }
};

function findPropBOfObject (object) {
  object.a || return;
  return object.a.b;
}

function unguardedFindPropBOfObject (object) {
  if (object.a && object.a.b) {
    return object.a.b;
  } else {
    return;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment