JavaScript if/else Vs. Ternary Operator

aaron brady
2 min readApr 30, 2021

Going through technical interviews, you meet a lot of programmers with a lot of professional experience. Having conversations with them can be very enlightening on how they operate in the real world of programming. In the latest technical interview I had, the interviewer and I had a conversation about using if/else conditionals compared to ternary operators. As their preference is to use if/else statements as the readability is better for other programmers to read and understand the written code. I was taught the less code you wrote, the better. I guess it just depends on who you ask. Although I can see how nested ternary conditionals can get messy, but again, it just depends on who is reading the code.

I have taken it upon myself to develop the versatility in using both methods. I believe developing both skills will help me understand the syntax better when writing conditionals.

I use a website called edabit.com where has thousands of challenges varying at different levels. My plan right now is to re-write every if/else statement to a ternary operator once I have passed the challenge.

The first challenge is to find out if a word is plural or not; returning true or false. I completed the challenge with the if/else method first:

function isPlural(word) {
if (word.endsWith('s')) {
return true
} else return false
}

This can be re-written to:

function isPlural(word) {
return word.endsWith('s') ? true : false
}

This in my opinion, is cleaner and learner and the readability is user friendly too.

Next challenge is to find the type of unevaluated operand in the functions fifth argument, if it exists. Writing it again with the if/else method:

function fifth(...args) {
if (args.length < 5) {
return 'Not enough arguments'
}
return typeof args[4]
}

Now with ternary:

function fifth(...args) {
return args.length < 5 ? 'Not enough arguments' : typeof args[4]
}

I honestly feel ternary is the best way to write simple if/else statements, although dealing with nested ternary operators can a bit messy, and I can see how some people with prefer if/else. Developing writing in both methods will help me be able to adapt to any environment that has a preferential choice.

--

--