Now if num
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 num === 5 || num === 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 take a closer look at TypeScript's types, and how they can work with control flow, as well as some other TypeScript-specific details.
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: