DEV Community

Cover image for Stop using if else
Rishav Jadon
Rishav Jadon

Posted on

Stop using if else

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('')
Enter fullscreen mode Exit fullscreen mode

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`
}
Enter fullscreen mode Exit fullscreen mode

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`
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading this short article, if you liked it, you can support my work at https://www.buymeacoffee.com/rishavjadon

Latest comments (65)

Collapse
 
danielgomezrico profile image
Daniel Gomez

Can you share why would this be more readable/maintainable? I'm worried about you saying that this is "more readable and maintainable" without giving quality arguments about why that's true, that may let people believe that this is a must always.

I just went into a discussion about this topic, and some people argue that:

const condition = true

const value = {
   false: "first",
   true: "second
}[condition]
Enter fullscreen mode Exit fullscreen mode

Is better than a simple if like:

const value = condition? "first" : "second"
Enter fullscreen mode Exit fullscreen mode

This is an abuse/overuse of a language feature or structure which involves more concepts and more time on your brain in order to understand what is happening when you read it.

I also believe that this enlarge possible problems in devs minds like "Primitive types obsession" and "Declarative Dilussion", check:

WDYT?

Collapse
 
dominikbraun profile image
DB • Edited
  • Using an object doesn't mean that you're doing OOP.
  • else if and Map 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.
  • The only thing you should actually stop is posting articles talking about "absolute" truths.
Collapse
 
rjitsu profile image
Rishav Jadon
  • it's not just using an object, it's the context in which you use it, so there's no need to say this isn't OOP, yes I gave a small example but you can see there are examples in the comments supporting the idea.
  • of course they're not fully interchangeable but in certain cases they are.
  • No one said it's bad, it's just better to use other alternatives where everything is being repeated.
Collapse
 
dannyengelman profile image
Danny Engelman

Interesting.. no one mentions the Minification proces, and how that optimizes your code.

Collapse
 
saroj8455 profile image
Saroj Padhan

Thank you

Collapse
 
pachverb profile image
new/bird

good,jobs. This idea is very good. Dictionary way, okay. The usage scenario in this way is to switch between different branches according to the incoming value. At that time, if you don’t pass in a value, you need to switch to a different branch, how to do ?

Collapse
 
thecodingcrow profile image
thecodingcrow • Edited

neat approach to improving readability (and apparently also efficiency), I like!

small suggestion from my point of view, you called the valid characters object listOfCharacters but I would rather go with validCharacters or sth similiar. Since the variable is technically not a list

Collapse
 
assunluis80 profile image
LuΓ­s AssunΓ§Γ£o • Edited

Sorry, but I don't agree at least with your example. Why not a switch case?

Collapse
 
rjitsu profile image
Rishav Jadon

That would also be almost like if else.

Collapse
 
assunluis80 profile image
LuΓ­s AssunΓ§Γ£o

Almost how? Did you meseare the performance? Can you be more specific?

Collapse
 
planet_cbx profile image
Charlène Bonnardeaux

Thanks for the tips today at work I remember I’ve see your article and that’s save my code of a bunch of if/else. ;)

Collapse
 
rjitsu profile image
Rishav Jadon

I'm glad it helped, thank u :)

Collapse
 
ghvstcode profile image
Oluwatobi

Stop telling me what to do

Collapse
 
rjitsu profile image
Rishav Jadon

Stop telling me to stop telling you what to do.

Collapse
 
ghvstcode profile image
Oluwatobi

πŸ˜‚πŸ˜‚πŸ˜‚πŸ˜‚πŸ˜‚πŸ˜‚πŸ˜‚ This is a good one ! Nice article mate.

Collapse
 
michaelcurrin profile image
Michael Currin

I suggest watching videos or looking at the blog of Uncle Bob, the Clean Coder. He also supports this view.

He suggests another solution - polymorphism. Not needed for a simple case of matching string results but if you had more complex logic it would be worth making classes which all implement the same method. And then you pass in a class instance to a function and it calls the method of the class - no need for if statement or keylookup.

It's possible too outside of classes - but probably requires type system from TypeScript and overloading function so you call a variation of a function depending what type you pass in.

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