Conditional logic in JavaScript is a very straightforward topic, and not much thought is put into approaching it. The if (){...}
statement is king! This is so because it is the most common, and simplest, way to conditionally run a block of code. While having popularity is one thing, being the generic best approach is another. Thinking beyond the if statement, at a certain point, I lean more into a well-written switch statement.
For added context, think of an if a tree with about four conditional branches.
if (...) {}
else if (...) {}
else if (...) {}
else {}
For most, this doesn’t look too bad. Honestly, it isn’t that terrible either. It gets the job done, and is quite understandable for most. The drawback that makes me want to look at alternatives, however, is how this looks as it expands and overall legibility. That’s why in larger conditional tree scenarios, I lean into using a switch statement.
switch(true) {
case condition1:
......
break;
case condition2:
....
break;
case condition3:
....
break;
default:
break;
}
For me, this approach is much easier to read past a certain amount of conditional branches are needed.