Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I always thought one of the main arguments for the guard pattern ("early exits" in the article) was _specifically_ to reduce nesting, so I find it interesting that both guard patterns and nested ternaries were mentioned. For complicated nesting that's nontrivial to simplify in this fashion, you should then think about extracting logic into helper functions.

(The example is also a bit misleading, since the logic flow between the nested ifs and the chained ternaries are subtly different.)

In the provided example, const result = !conditionA ? "Not A" : conditionB ? "A & B" : "A";

is really equivalent to:

  const result = null;

  if (!conditionA) {
    result = "Not A";
  } else if (conditionB) {
    result = "A & B";
  } else {
    result = "A";
  }
which I don't think is that bad (look ma! no nesting!). You could also use a function, especially if the logic is too complex to flatten reasonably:

  function checkConditions() {
    if (!conditionA) {
      return "Not A";
    }
    // A is true from here onwards.
    if (!conditionB) {
      return "A";
    }
    // B is also true from here onwards.
    return "A & B";
  }
  
  const result = checkConditions();


You're code example is technically nesting btw.

That language doesn't have an "elseif", so you're actually writing the shorthand for

    if(!a) {
      ...
    } else {
      if(!b){
        ... 
      } else {
        ...
      }
    }
Your point stands nonetheless. I just had to smile seeing that example




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: