Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 14, 2021 12:34 pm GMT

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('')

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


Original Link: https://dev.to/rjitsu/stop-using-if-else-264o

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To