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.

if statement
if (condition) { ... }

Consider the simple program below, which only performs the console.log instruction if the value in score is greater than 80.

let score = 85
if (score > 80) {
console.log('Good job!')
}
Click "Run" or Shift + Enter

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.

// Will not print scores of zero
let score = 0
if (score) {
console.log('Your score was ' + score)
}

// Will not print if last name not provided
const firstName = 'John'
const lastName = ''
if (firstName && lastName) {
console.log(`Your name is ${ firstName } ${ lastName }`)
}
Click "Run" or Shift + Enter

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.

const score = 90

if (score >= 90) {
console.log('You got an A')
}
else if (score >= 80) {
console.log('You got a B')
}
else if (score >= 70) {
console.log('You got a C')
}
Click "Run" or Shift + Enter

Typescript can make further inference on the data type of a value based on the evaluation of if and else if statements.

const amount: string | number = 123

if (typeof amount === 'number') {
console.log('$' + amount.toFixed(2))
}
// TypeScript infers that amount must now be a string
else if (amount.startsWith('$')) {
console.log(amount)
}
Click "Run" or Shift + Enter

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.

let i = 1
while (i < 10) {
console.log(i)
i = i + 1
}
Click "Run" or Shift + Enter

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.

// TODO

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.

const value: any = 1234

switch (typeof value) {
case 'string': console.log('value is a string')
case 'number': console.log('value is a number')
}
Click "Run" or Shift + Enter

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.

const value: any = BigInt('1234567890')

switch (typeof value) {
case 'string': console.log('value is a string'); break
case 'bigint':
case 'number': console.log('value is a number')
}
Click "Run" or Shift + Enter

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.

try {
JSON.parse('invalid')
}
catch (error) {
console.log('There was an error')
console.log(error)
}
Click "Run" or Shift + Enter

Was this page helpful?