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.
CodePudding user response:
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 if
s you could add code for condition true
.
CodePudding user response:
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())