Recently, I had a take home assignment for a front end role, and I had to make a sort of Dashboard. I thought I did everything right, but I was rejected, partly on my carelessness, and also due to my code. I was using too many if/else statements everywhere! And I didn't know any better. But now I do, and I'm here to share that with you.
Most of us use if/else and switch statements whenever there is some conditional logic to handle. Although it might be a good idea to do that for one or two conditions here and there, using multiple if else statements chained together or big switch statements will make your code look very ugly, less readable and error prone.
function whoIsThis(character) {
if (character.toLowerCase() === 'naruto') {
return `Hokage`
} else if (character.toLowerCase() === 'sasuke') {
return `Konoha's Strongest Ninja`
} else if (character.toLowerCase() === 'isshiki') {
return `Otsutsuki being`
} else if (character.toLowerCase() === 'boruto') {
return `Naruto and Hinata's son`
}
}
whoIsThis('')
You see that we are repeating ourselves many times by writing multiple console.logs and if statements.
But there's an Object-Oriented way of doing this, and that is by using Objects.
Instead of writing if else blocks we just define an object which has the values we use in comparisons as keys, and the values we return as values of the objects, like so:
function whoIsThis(character) {
const listOfCharacters = {
'naruto': `Hokage`,
'sasuke': `Konoha's Strongest Ninja`,
'isshiki': `Otsutsuki being`,
'boruto': `Naruto and Hinata's son`
}
return listOfCharacters[character] ?? `Please provide a valid character name`
}
By using objects, we were able to make a sort of dictionary to look up to, and not use multiple if-else statements.
We can also make this better by using the Map object instead of using an object. Maps are different from normal objects:
- They remember the original order of insertion
- Unlike objects, we can use any type of data as key/value, not just strings, numbers and symbols.
function whoIsThis(character){
const mapOfCharacters = new Map([
['naruto', `Hokage`],
['sasuke', `Konoha's Strongest Ninja`],
['isshiki', `Otsutsuki being`],
['boruto', `Naruto and Hinata's son`]
])
return mapOfCharacters.get(character) ?? `Please provide a valid character name`
}
Thanks for reading this short article, if you liked it, you can support my work at https://www.buymeacoffee.com/rishavjadon
Top comments (65)
I agree with what @bubster said. You should rename it to "stop abusing".
Plus I did some benchmarking. It seems like if/else is always the slowest, using a Map makes only a negligible difference in Firefox, and an object is much faster in Chrome. Test for yourself: jsbench.me/jekur7m830/1
(I modified your code a little bit to keep things fair. You called toLowerCase for every branch in the first example and didn't use it in the latter two. I also moved the declaration of the object/Map out of the function, otherwise it would be created for every iteration)
When adding more calls like
to each test case if/else actually wins in Chrome which makes me think if Chrome somehow caches it.
At large scale a lookup by key is far more efficient. At small scale it is maybe small difference.
If you had extreme case of code of say 1000 branches of if else statements, at worst it takes 1000 attempts until the last one matches.
While looking up a value from an object/map by key is constant - only needed exactly one attempt to find the result.
Oh my bad for not using toLowerCase in further examples! Thanks for the tip about moving the dictionary out of the function.
You agreed with the tip, but the code example is still not updated. It's better to make the change, so beginners can learn from better examples.
Btw, my other comment was referring to "Thanks for the tip about moving the dictionary out of the function."
Have a lovely day.
Ah! Sweet coding challenges. I still remember this CTO who wanted me to replace an if else statement using a strategy pattern... the code was 10 lines. How to introduce useless complexity 101.
Why? I mean if it's so ugly, less readable, and error prone, why so many programming language implement them?
The first solution is NOT an object-oriented solution. You're using a JS "object" as a poor man's map of sorts but you're not using anything remotely OOP.
I love this post. It’s missing a bunch of details, such as how you can use functions instead of strings to match the items, and that this is a contemporary implementation of a “Command Pattern.”
Many of the responses aren’t terribly helpful, and some are a bit on the rude side. We should be more willing to entertain someone else’s ideas than to simply shoot them down as many comments on this post do.
Rishav, your idea could use more fleshing out, but I like where you’re going with this. I would very much like to see you continue on this thought, and address how this pattern can lead to a reduction in cyclomatic complexity and an overall increase in testability of the function implementing this pattern.
Thanks Michael, yes the comments are filled with useless people just wanting attention. Still thinking about this and surely will provide a better version in the future!
It's okay to go looking for better solutions than just a chained if-else. On the other hand, many evils have been committed in pursuit of over-optimization, merely on the basis of the feeling that "real developers don't use if statements". Oh yes, we use them. Often. And liberally. And they work really, really well.
See also...
Six Things You Thought Senior Devs Did (But We Don't)
Jason C. McDonald ・ May 21 '21 ・ 3 min read
You mean that developers have a tendency to overly-complicate simple problems by implementing 10 ton hammer solutions? Pshaw! Haha, for the rest of us "normies" simple, repeatable, digestible, straightforward solutions are always preferable to the "smart" solution.
This only works if you're comparing a single variable with known values. For other cases you've to use if/else
Can you share any example where you cannot make use of this?
I meant a real example from code. Anyways, we need to write good code in order to not add conditionals like these.
This is a perfectly fine example of real code lol.
Here:
@naveennamani is right. There are ways to do things with an array, but it can sometimes get over complicated and unreadable.
There are still elegant ways to handle that kind of requirement within the function:
And this translated to the initial
a
andb
example becomes:I see your point, but what if there is a property that is completely unrelated to the other variables? It would be pointless to do it for each one.
With lookup maps approach you can drill down how much you wantt with minimal changes to the initial structure, so it would be something like this:
Now you can go even further and have multiple validity checks for example:
And sorry for jumping in like so in the thread, I just know that plenty of people are for some reason struggling with this approach and I found this example intriguing. Also want to add that there is no practical way to completely avoid
if/else
statements, I use both approaches in my every day coding, it's just a matter of improving readability and removing code duplication.If there's a simple
0
and1
check, I see no reason to use a lookup map for that case, I'd just write down a simpleif
.This comment, and example is the best to explain the concept, thanks for this!
@davidlazic are you saying i should replace
with
sure those are equivalent, but what above the functionality that i intended to run in the if condition, should I wrap them in anonymous functions and pass to another function. What about the else if condition? Should I call that like
if(example('b', b))
?
If all conditions has some common logic you can use mapping to bring the variability into the object and using the mapped values to execute the logic. But again, even if slight deviation is added (for example a console log in a single else if condition) then your common logic is not common anymore, and you have to add more hacks like anonymous functions as part of the mapping object and so on, as you just demonstrated in your example with validation functions.
The best practical example would be state management in redux, where switch case statements seems to be most efficient, readable and manageable, try implementing that with mapping.
Hey @naveennamani , appreciate the time you've taken to think about this. My comment was a reply, not a statement, where I simply described how a specific problem could be written in a different kind of way with an example. Like I wrote, I use if/else, switch and this kind of approach on every day basis, based on the situation. If a function is supplied with too much logic, there's probably something that's gonna go wrong and it could be split into separate pure parts.
Are we just going to skip over the fact that
switch
exists? Lookup maps have neat uses, sure, but declaring a best practice for something without mentioning the intended language construct for it is a bit silly.Good point, and thanks for sharing. But I think it only depends on the case you are working on. if/else can be easily abused as of any other tool. So I think we should really know our tools, and pick the right one for the job.
Thanks for sharing again, keep it up
You probably don't even need any
else
if you go with the bouncer design pattern.I will still prefer switch here:
or object literals
else if
andMap
both work for your case, but they're not interchangeable in general - one is a control structure and the other one is a data structure.else if
is not inherently bad, it can be the most precise solution for some specific problems.Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more