Else if statement vs ternary operators

Hello everyone I’m new to coding and have a question:

why would I use “else if” statements if I can just use ternary operators instead, it’s certainly easier, not to mention that the code looks better.

Consider that just like arrow functions are best suited to concise body, ternary statements are best suited to where there is a minimum of structure or verbosity. We are better off writing imperative code and then analyzing it, than writing expression based code and then trying to debug it/find issues.

Also, just like arrow functions were not intended to replace standard syntax, only lessen the load in those situations where it simplifies the code, ternary statements are not a replacement of if…else if…else; they also lighten the load in some cases.

A long time ago somebody suggested that code should read like a story. Well, that was back when there was a lot of spaghetti code and GOTO. In present day the demand for readability is shouted from the rooftops, down to the IF as opposed to, ?.

The key consideration might favor a collaborative environment as well as portability, which is write the if…else statement and be done with it. We can simplify those statements with smart returns which essentially remove them from the picture without a change in syntax. Something to consider?

Bottom line, this may be a lot of conjecture, and is largely opinion, so take from it what one may.

Thank you for the response, come think of readability is key in collaboration.

1 Like

A simple example that favors the ternary expression (and arrow function):

const black = '#000';
const white = '#fff';
const foo = x => x % 2 ? `black: ${black]` : `white: ${white}`;
const bar = x => x % 2 ? black : white;

If we run a loop over a sequence this will give us alternating results. We could use bar to generate a checkerboard, for instance. Can you imagine such a scenario?