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 trialjrabello
17,917 PointsElse if versus Switch statement
Hello everyone,
I'm brand new to web development, and I have developed software for a couple of years(C and C++) and I have NEVER in my life used a single "else if" statement.
When I need to compare a single value with multiple ones I always do a switch, It's more clean, faster(at least C compiler uses a jmp lookup table),and for beginners I think It's quite better to avoid confusion, so I REALLY think those videos about else if statement should be removed and replaced with a switch case.
So I'd like to ask people here what do you think about it?
Marcus Parsons
15,719 PointsKevin, they each have their different uses and neither one is less or more confusing than the other one. You just use whichever type fits the code you're checking better.
kevinardo
Treehouse Project ReviewerYes but in the context of explaining conditionals i think that explaining the if statement and then continue with the if else is the way to go thus making it less confusing then introducing the switch statement which's syntax is alot different.
I dont mean that they by themselves are confusing as a concept but the thread starter wanted to know if we think that the video about if else should be replaced with a video about the switch statement. And imo that would been confusing.
But... the best would be to include a video in this section After the if else video with the switch statement. Or in a workshop :) /rant
jrabello
17,917 PointsHey thanks everyone for the reply, I really think switch statement should be explained, and another thing that I'm REALLY missing in js course is RegEx!!!
Imho should be very interesting to add it to js basics course :)
Marcus Parsons
15,719 PointsYou're welcome, sir!
Absolutely! I agree that it deserves an explanation video and what its uses/limitations are.
matthewshear
9,229 PointsIt depends on the situation. I definitely use if else a LOT more than I use switch, but I do use both. If I only have one or two conditions, why would I use a switch?
9 Answers
Marcus Parsons
15,719 Pointsswitch
statements are useful for comparing a single variable against multiple possibilities. If you're using logic operators (other than a series of || "or" statements), you should abandon using the switch statement, though. Switch statements are readily able to evaluate || statements because you can cluster cases together so that if anyone of the cases is true, the code contained within will execute, such as this:
var name = 'Bob';
switch (name) {
//Alerts if the variable "name" is Bob, Robert, or Bobbert: "Bob's rule!"
case 'Bob':
case 'Robert':
case 'Bobbert':
alert("Bob's rule!");
break;
//Alert for any other value not listed in the cases: "Non-Bob's suck!"
default:
alert("Non-Bob's suck!");
break;
}
However, when using any other kind of logic, you'd have to make incredibly complex pieces of code to utilize switch statements that would completely abandon readability.
There are lots of cases where an else if
is superior to a switch
especially when you need to use other logic operators.
Take, for example, a sample out of my powerful calculator program:
//Insert Mod operator - Shift + 5
if (event.shiftKey && event.which === 53) {
changeButton($("#modbut"), "%");
}
//Multiplication - * key or Shift + 8
else if (event.which === 106 || (event.shiftKey && event.which === 56)) {
changeButton($("#multbut"), "*");
}
The first if statement checks to see if you pressed any shift key and the number 5 above the keyboard. If you did, it inserts the modulus operator %. However, duplicating just that if-statement alone with a switch statement is very tough. The second else if is part of a long series of else-ifs that check for keyboard input so that they can insert data into the calculator based upon what the user presses. It utilizes both || and && logic because a user can press the * key on the numpad or they can press shift and 8 to insert a * symbol for multiplication. You can't easily duplicate this code with a switch statement.
If you happened to go to my calculator program, you'll see that the series of else if
statements are followed by a very long switch
statement. The reason being is that in the case of what I needed, the switch
statement below the else-ifs provided everything I needed into a nice format because all I needed was || logic.
The moral of the story is to adapt what conditional you use to your needs and not claim a conditional is superior to another. Each of them have their different uses.
geoffrey
28,736 PointsNot sure that should be removed, It's pretty common to see cases where else if are used. Not teaching it would be a mistake and would propably make the course incomplete, at least that's what I personnaly think.
Finally, you are right, if you need to compare one single value with multiples ones, a switch is more suitable. It still depends on the numbers of comparisons I guess, but once again It's true that switches make the code more readable.
Here is my opinion, but I probably can't claim to have as much experience as you do in development.
kevinardo
Treehouse Project ReviewerHey guys. Vote for this to happen. https://trello.com/c/wylqC06q/44-workshop-the-javascript-switch-statement
I really like some of the recent workshops. I wish they could spit out even more content :D
jrabello
17,917 PointsGood, But I think doing a workshop is not enough, it MUST be added to the main JS course, both switch statements and Regular Expressions are VERY important things to know, and not only in js
Allison Walker
17,137 PointsDear Marcus,
It can be fun to participate in discussions, but I wish I had been able to share my opinion without someone feeling it needed correcting. It’s very discouraging.
Everything I had to say on the discussion topic was similar to the majority of everyone else’s responses. And at no point did I state that I did not have experience with switch statements. Yet, for some reason, even when I’d clarified my point, when you responded to me you made this statement, “I never said they should be skipped over at all lolz. I don't know where you got that from…”. You either forgot what the discussion was about, ironically (if not suspiciously), or you were intentionally being provocative, and your “lol/lolz” intentions may have been lighthearted, but they were at my expense. I also have to say, your final attempt at being “nice” is undermined by your haughty explanation of asinine.
If you actually forgot what the topic was before you replied to me, I would suggest taking more time to carefully read and consider what someone else has posted or written before replying or commenting, when participating in future discussions.
It’s also considered good etiquette to note when you’ve made edits/deletions to a previous posts on discussion threads. PS - I moved this down here, somehow posting to the thread moved it to the wrong spot.
Marcus Parsons
15,719 PointsYou have nothing better to do with your life, do you? lol
Marcus Parsons
15,719 PointsAs my niece would say, "Let it go...let it goooooo!"
nfs
35,526 Pointsthanks brand new guy, we got long discussion because of you...
Allison Walker
17,137 PointsIf you're an advanced programmer, switch statements vs if-else statements make a lot of sense. But, when you're first learning to program, you have to understand the basic concepts before you can move to something advanced.
I hope we learn switch statements later, but for a Basics course this makes sense.
Marcus Parsons
15,719 PointsSwitch statements aren't really an advanced concept, but I can see how that might look. I delved pretty deeply into the logic behind switch statements, but the actual syntax and use of switch statements is very straightforward. When you encounter learning switch statements and start using them, you'll pick up on it in no time.
Allison Walker
17,137 PointsMaybe, but it is a basics course. And my point is that this is an introduction to conditional statements, which is simpler to describe with if/else vs switch.
Plus many other programming languages use if/else. It wouldn't be right to skip over them.
Allison Walker
17,137 PointsMarcus, maybe you forgot that this was a question posed to everyone, which includes both advanced and beginning students. The proposal was to cut out if/else statements from a basic Javascript course and to use switch statements instead, and then asking the community what we thought about that idea. This proposal/question comes from someone who admits to being an advanced programmer, in another programming language. The idea of skipping if/else might make sense to someone who has a lot of programming experience, but it wouldn't make sense to someone who does not have a lot of experience.
My thoughts and experiences are perfectly valid, and I think the Treehouse instructors feel the same way or they wouldn't include if/else in this course. I don't appreciate the way you disqualify my statements with "lolz" and "lol" responses. I do not appreciate the reductive attitude you have towards my response by stating that "switch statement are very basic lol." You seem to have a lot of experience so I would think you would be able to show more sympathy when you respond to people who are still starting out. You don't need to explain your position to me - I'm not the one who asked the question.
Marcus Parsons
15,719 PointsI was nothing but nice to you. For you to come on here and attack me personally for saying lol and lolz is beyond asinine (FYI: asinine means extremely stupid). Nothing I said was directed at you, and that's obvious. I don't have to defend myself because your behavior is completely irrational. But now you've irritated me. So, I'm going to say "lol k bye".
Allison Walker
17,137 PointsMarcus, I've been civil enough. From my perspective, you're intentionally going out of your way to be antagonistic. If you continue, I will contact Treehouse Support to notify them of a possible violation of their Terms & Conditions.
There is no better use of one's time than to stand up for one's own rights.
Marcus Parsons
15,719 PointsI don't care what you do, Allison. You can't seem to "let it go" as Elsa would say, so you might as well let your soul continue to be Frozen. Also, I don't know what rights I have supposedly trampled, but your best bet is to contact Washington, D.C. and inform them that there is a guy on Teamtreehouse.com who is using witty banter to entertain himself with a fool. Good day, sir! =]
kevinardo
Treehouse Project Reviewerkevinardo
Treehouse Project ReviewerUsing if else as an example is in my opinion better and less confusing since Dave is using the if statement in this section. I think switch statements in JS are generally used when an if / if else starts getting way to big and complicated... Every up to date JS course only touches briefly on the switch statement from my experience.
I can't remember if they explain the switch statement here at treehouse in some JS course (i don't think so) and if so i think it would fit perfect as a workshop with the great @huston hedinger(can't @ him :O fix plx) or what say you Dave McFarland ? :)