Categories
Codes Javascript

Use This Instead Of If-Else and Switch-Case in JavaScript

“If you excessively concentrate on a closed door, you may miss the alternative easy entries!”

― Mehmet Murat ildan

Introduction

Conditional statements such as if-else and switch-case are one of the basics to learn in programming. They open an unlimited options of functionality in the program we run every day.

But, sometimes there are cases where writing if-then-else-if-then-else or switch-case-case-case feels too much. It looks ugly, yet we need it to program. And also, there’s much redundancy that makes the code feel harder to read.

In this post, I would like to share another way to write conditional statements without using if-else or switch-case.

The Problem With If-Else

This is an example if statement, in its most basic glory:

if (x === 'one') {
  return 1';
} else if (x === 'two') {
  return 2;
} else {
  return -1;
}

I’m very sure you know it. It’s the simple, understandable conditional statements. But, what if there are many choices? Let’s say, eight ifs? It would be something like this:

if (x === 'one') {
  return 1;
} else if (x === 'two') {
  return 2;
} else if (x === 'three') {
  return 3;
} else if (x === 'four') {
  return 4;
} else if (x === 'five') {
  return 5;
} else if (x === 'six') {
  return 6;
} else if (x === 'seven') {
  return 7;
} else if (x === 'eight') {
  return 8;
} else {
  return -1;
}

Why eight? Not ten? It’s because I’m a Chinese-born guy. Chinese loves number eight.

Put number eight aside, it’s a long stretch of ifs. And it’s ugly, so many redundant ‘else if’s. Can we cut some bytes int the code because of that statement?

The answer is yes.

The Problem With Switch-Case

And so, the usual go-to approach for long ifs for many programmers are: the rather prettier switch-case. And here is the switch-case form, with the same logic:

switch(x){
  case 'one': return 1;
  case 'two': return 2;
  case 'three': return 3;
  case 'four': return 4;
  case 'five': return 5;
  case 'six': return 6;
  case 'seven': return 7;
  case 'eight': return 8;
  default: return -1;
}

A bit shorter is it? Yes, it is. Is the problem solved? Yes, it does. But not in the way I like it. There’s still too much redundancies in the ‘case’s and ‘return’s. And also if you notice, I had not written any ‘break’s yet because of the returns. It would become something like this if it does:

let num = 0;
switch(x){
  case 'one': 
    num = 1; 
    break;
  case 'two': 
    num = 2;
    break;
  case 'three': 
    num = 3;
    break;
  case 'four': 
    num = 4;
    break;
  case 'five': 
    num = 5;
    break;
  case 'six': 
    num = 6;
    break;
  case 'seven': 
    num = 7;
    break;
  case 'eight': 
    num = 8; 
    break;
  default: 
    num = -1; 
    break;
}

It would be much longer than the ifs! And this is just a simple example.

This Is The Way

So, let’s look at the problem and find a new shorter, more beautiful solution. It would use the same logic, but in a simpler way of coding. And it should be much more readable, easier to maintain and modify either by you or the other programmers at work. This process is called refactoring.

The logic of the code is “There is a defined value for x. If it doesn’t, return a default value, which is -1.

My favourite approach of this problem is by using dynamic property access to an object (Read these tricks if you haven’t).

First, I would define all the values in an object. The next step is to create a function that would access the values. And then, add a default value in case of trying to get an undefined property.

Take a look at this example:

const xValues = {
  one: 1,
  two: 2,
  three: 3,
  four: 4,
  five: 5,
  six: 6,
  seven: 7,
  eight: 8
};

const getX = (x) => {
  return xValues[`${x}`] || -1;
};

console.log(getX('eight')); // 8
console.log(getX('twentytwenty')); // -1

Ah, such an elegant code (if you know a better one, please teach me master!), so satisfying!

So with this approach, should you need to add a new value, for instance, a nine or ten, you can add them inside xValues object. The only redundancies are the “:” and “,“, compared to else ifs with the else and if, or switch-cases with the case, break, or return.

And, if you are curious to compare the total of bytes used in the three approaches, the dynamic property access’ way is smaller (177 bytes) even that it’s completed with a function, compared to if-else (345 bytes), switch-case (243 bytes), and switch-case with break (413 bytes). I checked the codes using this site.

Conclusion

Personally, once I discover the dynamic property access way, I became rather unmotivated when using if-else on switch-case. It doesn’t mean if-else is bad though. Depending on the cases and code readability, I still use if-case if the conditions are not many. Usually I set a limit of two conditions, more than that, I would switch to dynamic property access.

I’m very sure there will be more interesting tricks in the future, as long as JavaScript are getting updates. Well, I hope it’s quite enlightening to you!

Do you have some better rules? Please don’t hesitate to share in the comments below!

Live the way to be your code, and code your life with it!

“To express the same idea in still another way, I think that human knowledge is essentially active.”

― Jean Piaget

By Ericko Yap

Just a guy who is obsessed to improve himself. Working as a programmer in a digital banking company. Currently programming himself in calisthenics, reading books, and maintaining a blog.

Leave a Reply

Your email address will not be published. Required fields are marked *