Development · August 2020

A Beginner's Guide to Javascript Conditionals

Learn and understand the different Javascript conditional functions - like if/else and swith/case - and how to use them in everyday scenarios

Joaquim da RosaDeveloper

Since the dawn of the digital era, programmers have been picking sides in several wars. We’ve got the Tabs vs Spaces, Emacs vs Vim, MacOS vs Windows vs Linux, white mode vs dark mode and many more. There’s one that really caught my interest. It’s one that I can’t really pick a side on. The one I’ll talk about is the war between the if/else statement and the switch case statement.

There are a lot, and I really mean a lot of new Front-end Developers. People get the hang with HTML/CSS, they learn a bit of Javascript and they are hooked. There’s just one problem. Normally, they tend to skip ahead a lot of steps while learning something. Front-end developers that didn’t learn Javascript in depth, never truly learned how if/else and switch truly works and how they manage data. I once fitted into this category, I struggled over studying about the subject and will try to make it simple for you - explaining as I wished someone had explained it to me. 

Both these statements in Javascript are constructs that generate a result, depending on a condition.

The If/else statement

The if/else statement, is the more newbie friendly one. 

1function ifSearchFor(person) {
2 if (person === "Fred") {
3 return "Fred's here"
4 }
5 if (person === "Danilo") {
6 return "Danilo's here"
7 }
8 if (person === "Brandão") {
9 return "Brandão's here"
10 } else {
11 return "We are Significa"
12 }
13}
14
15ifSearchFor("Danilo")
16
17//Danilo's here

It takes a condition, returns a result and, if we want, we can program the result we want to have, in case that condition is false.

The switch case statement

The switch case, unlike the if/else statement, looks a bit more complex

1function switchSearchFor(person) {
2 switch (person) {
3 case "Fred":
4 return "Fred's here"
5 case "Danilo":
6 return "Danilo's here"
7 case "Brandão":
8 return "Brandão's here"
9 default:
10 return "We are Significa"
11 }
12}
13
14switchSearchFor("Danilo")
15
16//Danilo's here

In this case, we have a main condition that might have one of many values. The code that runs, is the one in the case that is true. 

Comparison

Now, you might think: “Ok, they are pretty much alike, but if/else looks easier to use”. That’s true, and that’s why newbies love if/else over switch. If/else statements are pretty straightforward, easier to debug and better to use when the result of the condition is boolean (true or false).

In terms of speed, if we compare running three conditions in both if/else and switch case we can see that if/else is faster.

1const iterations = 10000
2console.time("If/else")
3for (var i = 0; i < iterations; i++) {
4 ifSearchFor()
5}
6console.timeEnd("If/else")
7
8console.time("Switch case")
9for (var i = 0; i < iterations; i++) {
10 switchSearchFor()
11}
12console.timeEnd("Switch case")
13
14// If/else: 1.1689453125ms
15// Switch case: 1.181884765625ms

If/else is, in theory and in most cases, faster than switch (by some nanoseconds)."Ok, if/else is always faster than switch". Wait a minute! Let's increase the number of conditions of both functions:

1function ifSearchForBig(person) {
2 if (person === "Fred") {
3 return "Fred's here"
4 }
5 if (person === "Brandão") {
6 return "Brandão's here"
7 }
8 if (person === "João") {
9 return "João's here"
10 }
11 if (person === "Lisa") {
12 return "Lisa's here"
13 }
14 if (person === "Catarina") {
15 return "Catarina's here"
16 }
17 if (person === "Márcio") {
18 return "Márcio's here"
19 }
20 if (person === "Rui") {
21 return "Rui's here"
22 }
23 if (person === "Danilo") {
24 return "Danilo's here"
25 } else {
26 return "We are Significa"
27 }
28}
29
30function switchSearchForBig(person) {
31 switch (person) {
32 case "Fred":
33 return "Fred's here"
34 case "Brandão":
35 return "Brandão's here"
36 case "João":
37 return "João's here"
38 case "Lisa":
39 return "Lisa's here"
40 case "Catarina":
41 return "Catarina's here"
42 case "Danilo":
43 return "Danilo's here"
44 case "Márcio":
45 return "Márcio's here"
46 case "Rui":
47 return "Rui's here"
48 default:
49 return "We are Significa"
50 }
51}

Now, let's run the same type of test we did before, and see which one is faster:

1const iterations = 10000
2console.time("If/else")
3for (var i = 0; i < iterations; i++) {
4 ifSearchForBig()
5}
6console.timeEnd("If/else")
7
8console.time("Switch case")
9for (var i = 0; i < iterations; i++) {
10 switchSearchForBig()
11}
12console.timeEnd("Switch case")
13
14// If/else: 3.76513671875ms
15// Switch case: 2.365966796875ms

Generally speaking, when if/else statements are used with more than three conditions the code starts looking a bit more complex, difficult to manage and the whole function’s speed is affected. The difference can be more noticeable, by all means, once the logic of the condition gets even more complex. Therefore, the if/else statement will be a lot slower than a switch case. Crazy, right? Well, that's just the way the compiler reads and digests your code. But I'll get there in a sec.

What to use

So, which one should I use? This question probably gets in your head every time you need to deal with a conditional.

Tweet by Kumar Abhirup

Honestly, I believe there's a place for both, as they both have their pros and cons. The objective is to use them on the right occasions

You should probably use if/else if: 

  • The condition result is a boolean;
  • The condition has up to three results;
  • You have some results that return the same.

On the other hand, you should use switch case if you:

  • Have a big array of possible results for your condition;
  • Are working with Big Data;
  • Have a lot of results that return the same.

So, all this sums up this eternal war for you. Have you picked a side? Don't do it yet!

You see, there’s a third champion that is sometimes forgotten when dealing with data flow control.

The Third Champion

This third way of managing data flow, introduces a concept that few Javascript programmers know, which is Branchless Programming. This concept, highly known in languages like C, C++ and Java, is mostly known by its high performance value. The objective is to create functions that don’t use branches. In the case of if/else and switch, each condition is a new branch. We can stop using so many conditions by using an Array Lookup.

Imagine I have a question and I’m looking for my fellow developer Danilo, to help me out. An if/else statement can be used to look for him. 

If/Else Statement

As you can see, I’m looking for him asking each and every one of the eggs if they are Danilo. This can be really tiresome, especially if I have a big team right?

The next example describes the behaviour of the switch case. I already know who Danilo is, so I look for him by going to every one of the eggs and when I find him, I’ll ask him my question.

Switch Statement

Have you noticed that the function stopped as soon as I found Danilo? This is another thing that makes switch functions have a higher performance than if/else. Well, you can always use an if/else if/else function. The compiler will treat it pretty much as it treats a switch function, ending the function as soon as it finds the desired result.

The way the data is controlled, in these situations, is designated as “linear search”. As the name suggests, the data follows a line and has several “checkpoints” that might dictate the way it will flow next. 

The Array Lookup, controls data in a way that can be called as “specific search”.

To do so, we need an array or an object, and, to call a specific result, we run an array result

1const team = {
2 "Fred": "I'm Fred",
3 "Brandão": "I'm Brandão",
4 "João": "I’m João",
5 "Danilo": "I’m Danilo",
6 "Lisa": "I’m Lisa",
7 "Catarina": "I’m Catarina",
8 "Márcio": "I’m Márcio",
9 "Rui": "I’m Rui",
10 default: "We are Significa"
11}
12
13function arrayLookup(person) {
14 return team[person] || team.default
15}
16
17arrayLookup('Danilo')
18
19// I'm Danilo

Clean, less code and, the most important part, it's super easy to maintain! If you have to add a team member by any change, you just have to edit the object. The function is pure and never needs to be updated. But what about performance speed? Let's take it for another run and test the function speed using the console.

1const iterations = 10000
2
3console.time("Array Lookup")
4for (var i = 0; i < iterations; i++) {
5 arrayLookup("Danilo")
6}
7console.timeEnd("Array Lookup")
8
9// Array Lookup: 0.85791015625ms

It's way faster than the if/else and switch case. This happens because what it does ‘behind the scenes’ is to call for the result. In this method, we call for a specific result.

Array Lookup

As you can see, instead of trying to search for Danilo by going to each egg, I can simply call for him to help me. Using this in conditional functions will highly increase their performance. This way, you will skip the other conditions and go right to the one you need. It's a more efficient way of writing code.

Ending Statement

As the web keeps evolving, and our databases/structures keep growing, we tend to need our code to be as fast as it can. A few milliseconds might look too small to care, but, in a whole, these small changes can shorten the speed data is handled. By using the array lookup method, you will get faster results, and still keep your code simple and easy to understand. Basically, it’s the best of if/else and switch case. Even though this is what I conclude with my search, there’s no “right way” to do it

Every case requires a specific solution, and I hope that, when a problem comes up, you will cast this war aside and pick the right champion for that situation.

References:

https://www.oreilly.com/library/view/high-performance-javascript/9781449382308/ch04.html

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else

https://www.differencebetween.com/difference-between-if-else-and-vs-switch/

https://www.geeksforgeeks.org/switch-vs-else/

JavascriptFor Beginners

Joaquim da Rosa

Developer @ Significa

Born in a traditional fisherman community, the Caxinas, Joaquim has got the fisherman's beard but that's all, really. Instead of using the net to catch fish, he uses the internet to get some React code going on. He's a Front-End Developer.