Switch Case vs If-else Statement (Which is optimized)

Switch Case vs If-else Statement (Which is optimized)

ยท

3 min read

Alright, I came up with a new topic, the Switch case vs if-else statement which is a more optimized way to write the code. In my opinion, we can't compare that two features every time because both have a little bit different workflow.

Like switch, the case has a break keyword to leave the switch block and also has one special case default means if the provided case didn't match then go with the default one where we can write write write error handling as well.

const fruit = 'apple';
switch (fruit) {
  case 'banana':
    console.log('The fruit is a banana.');
    break;
  case 'apple':
    console.log('The fruit is an apple.');
    break;
  default:
    console.log('The fruit is not a banana, apple, or orange.');
}

But the If-else statement doesn't have those things. It's just multiple conditions to check if something matched the code flow that will enter that block.

const age = 25
if (age >= 18) {
    print("You are an adult.");
} else {
    print("You are not an adult yet.");
}

But I have one good example in which both things are interchangeable that is the reducer function in redux.

const initialState = { count: 0 }
const counterReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return {
        ...state,
        count: state.count + 1
      }
    case 'DECREMENT':
      return {
        ...state,
        count: state.count - 1
      }
    case 'RESET':
      return {
        ...state,
        count: 0
      }
    default:
      return state
  }
}
export default counterReducer;

And the same function can be written in if-else.

const initialState = { count: 0 };
const counterReducer = (state = initialState, action) => {
  if (action.type === 'INCREMENT') {
    return {
      ...state,
      count: state.count + 1
    }
  } else if (action.type === 'DECREMENT') {
    return {
      ...state,
      count: state.count - 1
    }
  } else if (action.type === 'RESET') {
    return {
      ...state,
      count: 0
    }
  } else {
    return state
  }
}
export default counterReducer;

If you don't know redux any need to go into detail about the reducer thing we can just focus on that we have real-life examples even though both have different syntax.

In terms of optimization, both work similarly as the JS engines handle it properly. However, switch-case statements may be more readable and easier to maintain when dealing with a large number of conditions or cases, especially if they share common code blocks. In contrast, a series of nested if-else statements can become difficult to read and maintain over time.

Conclusion

Ultimately, the choice between using if-else or switch-case should be based on the specific requirements of your code and your personal preference. It's important to write code that is both efficient and easy to read and maintain.


Note: As I am learning python so I have a small tip for that in python we don't have the functionality of switch-case but if we want to implement I have a little hack ๐Ÿคช. Just have a look -

def zero_func():
    return 'Zero'

def one_func():
    return 'One'

def two_func():
    return 'Two'

def default_func():
    return 'Invalid input'

options = {
    "zero": zero_func,
    "one": one_func,
    "two": two_func
}

result = options.get("one", default_func)()

print(result)  # Output: 'One'

I hope you like this article and found it helpful. Thank You ๐Ÿ™

Did you find this article valuable?

Support Madhu Soodan by becoming a sponsor. Any amount is appreciated!

ย