← All articles

/ Shane Tarleton

Please stop using nested if statements.

Remove the nesting and use ternaries instead.

  • JavaScript
  • Code readability

Remove the nesting and use ternaries instead.

Image of code on a notebook screen.

Photo by Marc Mueller on Unsplash

It is harder to read code than to write it.
 — Joel Spolsky

I can’t tell you how many times I have run across something like this:

function getDocuments(onlyWord) {
  if (onlyWord) {
    if (isAdministrator) {
      return getWordDocumentsAsAdmin();
    }
    else {
      return getWordDocumentsForCurrentUser();
    }
  }
  
  return getAllDocumentsForCurrentUser();
}

Original gist: getDocuments_nestedIf.js

While this is a simple example, let’s rewrite this and take out the nested if statements:

function getDocuments(onlyWord) {
  if (onlyWord && isAdministrator) {
    return getWordDocumentsAsAdmin();
  }
  else if (onlyWord) {
    return getWordDocumentsForCurrentUser();
  }
  
  return getAllDocumentsForCurrentUser();
}

Original gist: getDocuments_nonNestedIf.js

That’s better. Now, we can get a better understanding of when each function call is returned, but I think we can easily do better. Let’s try and turn this into a ternary statement and keep the nesting out:

function getDocuments(onlyWord) {
  return onlyWord && isAdministrator ? getWordDocumentsAsAdmin()
    : onlyWord ? getWordDocumentsForCurrentUser()
    : getAllDocumentsForCurrentUser();
}

Original gist: getDocuments_ternary.js

If you don’t agree with me, that is okay. Everyone is allowed to write code how they see fit and this is absolutely NOT a one-size-fits-all and won’t work in every situation. I would love to hear your thoughts!