Now if number
is either 5 or 10, it will log Number is 5 or 10!. The reason is case 5 is allowed to fall through to case 10 and run the same line of code. It's similar to an 'if' statement with the condition number === 5 || number === 10
.
Why use a switch
statement? It can be a concise way to match a long list of possible values. However in many cases a series of 'if/else if' statements will do the same job. It's another kind of style choice. It's worth knowing how switch
statements work as they are commonly used so you're likely to come across them.
Conclusion
In this part we've covered various features that control how code executes, also known as control flow, including:
- 'if' statements
- 'else' and 'else if'
- Formatting (such as whitespace and optional braces)
- A simple 'Guess the number' game
- 'while' and 'for' loops
break
and continue
switch
statements with case
and default
labels
In the next part we'll look at another core building block of programming: functions! We'll also move on to using script files instead of a snippet of code in an event sheet.
Learn more
If you want to dig deeper, you can learn more about the features mentioned in this guide at the following MDN Web Docs links:
Part 5
When you're ready to continue, head on to the next part at Learn JavaScript in Construct, part 5: Functions!