DEV Community

Cover image for Alternative to if/else blocks
Ahmed Yagoub
Ahmed Yagoub

Posted on

Alternative to if/else blocks

Introduction

We often overuse if/else blocks. We use them throughout our code base every time we want to run optional block of codes or return different outputs based on an input value or a condition.

Example

Let's say I have a function that takes an input (string) and modifies that string.

To keep things simple, the function receives a week number, week 1 and should return week one

Using an if/else conditionals, we can have code like so

    function CurrentWeekLabel(value) {
     let weekNumber = value[value.length - 1]
     if (weekNumber === '1') {
       weekNumber = 'one'
     }
     if (weekNumber === '2') {
       weekNumber = 'two'
     }
     else if (weekNumber === '3') {
       weekNumber = 'three'
     }
     else if (weekNumber === '4') {
       weekNumber = 'four'
     }
     else if (weekNumber === '5') {
       weekNumber = 'five'
     }
      return value
        .slice(0, -1)
        .concat(weekNumber)
    }
Enter fullscreen mode Exit fullscreen mode

This function serves us well. However, there is an alternative that is less cluttered, less repetitive and more readable.

Alternative

We can use object lookups as an alternative, which is cleaner

   function CurrentWeekLabel(value) {
      let weekNumber = value[value.length - 1]
      let options = {
        '1': 'one',
        '2': 'two',
        '3': 'three',
        '4': 'four',
        '5': 'five',
      };
      return value
        .slice(0, -1)
        .concat(options[weekNumber] || weekNumber)
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)