Branching
Branching statements determine how a program makes decisions and repeats actions.
By evaluating conditions (true or false statements), a program can choose different paths of execution. If you are familiar with JavaScript or a programming language like C++ or Java, you are most likely already familiar with all of the branching statements listed here.
If statements
An if
statement executes a block of instructions if the given condition is true. A block is a group of instructions in curly braces ({
and }
), and a condition is any true or false value.
Consider the simple program below, which only performs the console.log
instruction if the value in score
is greater than 80
.
Recall from the basics that JavaScript considers empty strings and zero to be false values, and non-empty strings/non-zero values to be true values.
Else-if statements
An else if
statement after an if
statement provides an alternate condition and set of instructions to execute.
The condition is only evaluated if the condition in the previous if
statement evaluated to false. There can be
any number of else if
statements after an if
statement.
Typescript can make further inference on the data type of a value based on the evaluation of if
and else if
statements.
Else statements
An else
statement indicates a group of instructions to perform if no preceding if
or else if
condition was true.
While loops
A while
statement repeats a block of instructions as long as a given condition is true.
A while loop generally has three components - the initialization, the condition, and the increment.
It is important that the condition eventually becomes false, or the program will endlessly repeat the instructions and not do any further work.
For loops
A for
statement is a concise way to write the initialization, condition, and increment of a looping statement.
Notice that we can write the equivalent for
loop and while
loop below.
Do while loop
The do
and while
statement.
Switch statement
The switch
statement selects instructions from a list of case
statements.
TypeScript can help you write switch
statements and ensure that all cases are handled.
Notice that if you change the value
to a string, it performs both console.log
statements. Until a switch
statement encounters a break
statement, it will continue to perform the instructions of each subsequent case.
Try and catch
When an instruction might produce an error, a try
and catch
statement can define some custom error handling logic.
When a try-catch statement is executed, the instructions in the try
block are executed in order. If any instruction produces an error, the catch
block is executed with error
as the first parameter.