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 JavaScript Basics (Retired) Making Decisions with Conditional Statements Programming Multiple Outcomes

Programming Multiple Outcomes

Wouldn't a switch statement be better than using a if else/if else structure?

1 Answer

It depends on the situation. If you branch based on the exact value of a variable, you might want to use a switch:

switch (eventType) {
case 'click':
    console.log('You clicked something...');
    break;
case 'keydown':
    console.log('You typed something...');
    break;
default:
    console.log('I don\'t know what you just did, but it\'s cool...');
    break;
}

Here is an equivalent if-statement:

if (eventType === 'click') {
    console.log('You clicked something...');
} else if (eventType === 'keydown') {
    console.log('You typed something...');
} else {
    console.log('I don\'t know what you just did, but it\'s cool...');
}

The if-version might be shorter, but I still find the switch-statement easier to understand, because it better conveys the intention of the programmer.

Now, if the conditions in your if-statement don't have the structure varName === literal, you should not use a switch. By the way, by literal I mean fixed numbers, strings and so on. Another variable would not be a literal. Here is an example:

if (number < 42) {
    console.log('Think bigger!');
} else if (number > 42) {
    console.log('That\'s too big!');
} else {
    console.log('Just about right.');
}

The equivalent switch-statement is rather weird. Note that we are not switching on a variable anymore and that instead the case-conditions include variables:

switch (true) {
case number < 42:
    console.log('Think bigger!');
    break;
case number > 42:
    console.log('That\'s too big!');
    break;
default:
    console.log('Just about right.');
    break;
}