Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

To use if else conditional statements or switch case. General Talk

This is not a question but rather a brief discussion about the benefits of using switch case statements over if-else. I have found that switch statements are especially effective when it comes to JavaScript (might be different in other programming languages).

Regardless of whether the first condition is true or false in an if-else condition, the browser interpreter will read the script and test each of the conditions, even if the first condition is a match.

There are some disadvantages:

1) All the conditions are read -- takes up memory and less efficient 2) Can lead to slower page load time if complex

Switch statements seem to solve this problem because they break out of the conditions as soon as a match is found, therefore ignoring all other conditions. However, this does not mean that we should completely ignore if-else.

In some scenarios which test for several conditions with the utilization of logical operators to combine expressions, it seems feasible to make use of if-else.

What are your thoughts? Write below. I am interested in finding out what others think. Moderators are welcome and would be great to get some input.

Kind regards.

Here is some basic code to try out in the console with switch statements that I created. Just copy and paste into the broswer console:

var myStore = {

    quiteStore: 'false',
    showList: 'false',
    showPrompt: 'false'

}

let shopList = ['apple', 'pear', 'banana', 'orange', 'grape', 'broccoli', 'butter', 'egg', 'flour', 'watermelon', 'cherry', 'strawberry', 'bread', 'fish', 'ice cream'];

function runShop() {

    var askUsr = prompt('Search the shop. Type "quit" to exit the shop and "list" to show the available items in store.').toLowerCase();

    switch (true){

        case (askUsr === 'quit'): 
            myStore.quiteStore = true;
            break;

        case (askUsr === 'list'): 
            myStore.showList = true;
            console.log(shopList);
            askUsr;
            break;

        case (askUsr !== 'list' || askUsr !== 'quit'): 
            console.log('Error. No match found!');

        default: 'Error! Please try again later.';
        break;
    }

}

Please make sure to run this code by typing the following into the console in the browser:

runShop();

3 Answers

Steven Parker
Steven Parker
231,275 Points

This statement caught my attention:

Regardless of whether the first condition is true or false in an if-else condition, the browser interpreter will read the script and test each of the conditions, even if the first condition is a match.

This is not correct. When you have an "if/else if" chain, and the first condition is a match, none of the remaining conditional expressions get evaluated. You can demonstrate this easily:

var a, b, c;
a = b = c = 0;
if (++a > 0) console.log("a");
else if (++b > 0) console.log("b");
else if (++c > 0) console.log("c");
console.log(a, b, c);

This will first log "a", indicating that the first condition was met, and then log "1 0 0" indicating that no other expression was ever evaluated.

Steven Parker
Steven Parker
231,275 Points

Update

Out of curiosity, I also ran a benchmarking test comparing the performance of a 7-item switch with a 7-tier "else if" chain.

In several runs, the "winner" (always by a tiny amount) would sometimes be the switch, and sometimes the chain. So there's no detectable performance advantage.

I've heard that when there are a large number of conditions (perhaps a benchmark test for someone else!), a switch might perform more efficiently, but then there are ways to optimize chains that cannot be done with a switch.

Oh that is interesting. Yes there are a lot of blogs and posts online that confirm switch statements more efficient + good readability too. But as you mentioned, both have their pros and cons.

I read it from a book by Jon Duckett. He says the following in his book,

" with a series of if statements, they are all checked even if a match has been found (so it performs more slowly than switch".

Reference: Jon Duckett JavaScript book, page 164.

So yes you are partially right, while it is not 'evaluated' to return a value per se, the conditions are all still checked but only returns the matcged one. However, a switch statement only the matched one is checked.

Steven Parker
Steven Parker
231,275 Points

I don't know what you mean by "checked".
If it's something that happens before evaluation, how could it determine whether to do it with just the first expression and not the others?

Checked I guess what he means is the conditions are evaluated to see of they are true or false. In if else they are all evaluated regardless of whether there is a match or not

But i know what you mean by the fact that it needs to check them before it knows which one to return. Honestly i am quite confused on that matter. But that is what i have read from the book. He is very popular author for javascript

Steven Parker
Steven Parker
231,275 Points

The demonstration program in my answer shows that they are not evaluated to see if they are true or false.

I need to look it up more. I feel so lost about this topic. But generally speaking, switch statements have been super easy and amazing to write out for both clarity and efficiency.

But I cannot give a definite answer between if-else and switch. I need to read up on it more. Its just I came across that quote in the book, it got my attention.

Steven Parker
Steven Parker
231,275 Points

It gets my attention as well, because it is apparently incorrect.

That is very strange. Why would the author incmude such thing in the book if it is incorrect. Hmm I need to look this up more once I have the time.

Steven Parker
Steven Parker
231,275 Points

I'm wondering if the book included a code example of the "series of if statements"? Perhaps I'm doing something different from what he's talking about?

Also, how old is the book? Maybe JavaScript engines of that time had some efficiency problems that were later resolved.

Sorry Steven, I am not home at the moment. But I will definitely send you the code he has used if any. Also, the booked was published 2013.