GoConqr has a new look! Let us know what you think.

Module 11 of 18 · Media

Switch

Kostas Diakogiannis

Switch

Switch-Cases

Switch cases are another way to implement decision making in JavaScript in a little bit different way than if-else statements.

To be completely accurate is just a syntactic sugar. That means that logic-wise nothing changes fundamentally, JavaScript just provides us with something that looks more elegant syntax-wisely.

But when is more appropriate to use a switch-case syntax in favor of a if...else statements?

The answer is when you want to check multiple if statements, and you check the same variable over and over again if it contains a specific value. In our case we have rewritten the bands based on favorite color example, in a switch-case mode. 

Note the break keyword. This prevents further execution when a condition is met. That means if your favorite color is green, then the corresponding code is executed 'Green Day' and stops there. If the break keyword inside the case is omitted, then we will also go further and execute the purple case!

The default case is not mandatory, but it acts like a backup code that will be executed if all previous cases evaluate to false.

The benefit is a cleaner and easier to read structure that enhances debugging experience. Curly braces is not needed and the programmer is allowed inside a switch-case block to write code that looks similar "python-ruby" style.

Instructions

You must submit an attempt for this quiz to progress. You can submit it after the last question.

Go to the chosen module

Feedback

What is it about?

What do you think of the new look?

How do you like it?