Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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;
}