1

Given the following code:

if (CONDITION1) {
  if (CONDITION2) {
    if (CONDITION3) {
      if (CONDITION4) {
        if (CONDITION5) {

        } else {
          return ('STOP IN CONDITION5')
        }
      } else {
        return ('STOP IN CONDITION4')
      }
    } else {
      return ('STOP IN CONDITION3')
    }
  } else {
    return ('STOP IN CONDITION2')
  }
} else {
  return ('STOP IN CONDITION1')
}

I need to replace these multiple if statements for some other code using good practices and for cleaner reading for other people in future.

3
  • 3
    The elses are likely unnecessary. Try if(!condition) { return ... }? Commented Feb 2, 2023 at 1:34
  • If the if conditional is not doing anything, you could even drop the curly braces (and the grouping operator as well): if(!conditionX) return "stop in conditionX";. Commented Feb 2, 2023 at 1:44
  • 1
    Please don't drop the braces as suggested above. It looks horrible, it's easier to make mistakes and most linters require them by default. Commented Feb 2, 2023 at 3:10

3 Answers 3

4

You could flatten this by testing for not condition:

function doStuff() {
  if (!CONDITION1) {
    return ('STOP IN CONDITION1')
  }

  if (!CONDITION2) {
    return ('STOP IN CONDITION2')
  }

  if (!CONDITION3) {
    return ('STOP IN CONDITION3')
  }

  if (!CONDITION4) {
    return ('STOP IN CONDITION4')
  }

  if (!CONDITION5) {
    return ('STOP IN CONDITION5')
  }
}

Note: in between the ifs you could add code for condition true.

Sign up to request clarification or add additional context in comments.

Comments

0

This has already been answered and I wouldn't recommend this version (linters probably complain, flat if statements are fine) but I'm throwing it in there to show another possibility.

You can potentially use a switch statement and add your conditions to each case:

const CONDITION1 = 1 > 2
const CONDITION2 = 2 < 1

const run = () => {
  switch(true) { // always evaluate this switch
    case !CONDITION1: 
      return 'STOP IN CONDITION1'
    case !CONDITION2:
      return 'STOP IN CONDITION1'
    // etc...
  }
}

console.log(run())

Comments

0

Using Array.prototype.findIndex()

  • Store your conditions into Array
  • Use Array.prototype.findIndex(). Just return the argument itself (x) => x, it fill be treated as boolean and if true the method will return the index. Store the returned integer into a variable errIndex.
  • If errIndex is greater than -1 that means you have an "error" in the conditions array at that index

const conditions = [false, false, true, false, false];

const errIndex = conditions.findIndex(x => x);

if (errIndex > -1) {
  console.log(`STOP IN CONDITION ${errIndex + 1}`);
} else {
  console.log("All passed");
}

The nice thing about using .findIndex() is in that it can short-circuit the search and immediately return the index.


Not sure why, but given you want to return a String, and since return statements are used within a function, and since it's always preferable for a function to return the same type,
you could create a function that accepts an array of conditions and a success string as the second argument:

const status = (conditions, successMsg) => {
  const idx = conditions.findIndex(x=>x);
  return idx < 0 ? successMsg : `STOP IN CONDITION ${idx+1}`;
};

console.log(status([false, false, true, false, false], "OK"));  // STOP IN CONDITION 3
console.log(status([false, false, false, false, false], "OK")); // OK

or you can create something similar based on the above idea, like a pass function in which you do not hardcode error strings, but instead it provides you with a callback function with argument being an Object with index property or null

const pass = (conditions, fn) => {
  const index = conditions.findIndex(x => x);
  fn(index < 0 ? null : {index});
};


pass([false, false, true, false, false], (err) => {
  if (err) {
    console.log(`STOP IN CONDITION ${err.index + 1}`)
    return; // Exit function here
  }
  // All OK...
  console.log("All OK! Do some work here");
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.