Functions

A function is a sequence of instructions that can take inputs and produce outputs.

A function must first be defined before it is called (i.e. told to perform its instructions). In the previous lessons, you were calling functions that were defined by the programming language - now we'll look at how to define our own.

Loading TypeScript...

Defining functions

A common way to define a function is with a function type expression.

After the keyword function, the unique name of the function is specified, followed by any inputs that it takes (called parameters). For each parameter, we specify the data type that an input value (called an argument) will have.

Loading TypeScript...

A function can have multiple parameters, separated by a comma (,).

Loading TypeScript...

Return types

A function can produce an output value with a return statement.

Once the return statement is performed, no further instructions in the function are evaluated. The return value is used as the computed result of the function call.

Loading TypeScript...

There are multiple ways to fix the program below so the race finishers are printed in the correct order.

Loading TypeScript...

If a function parameter has multiple possible data types, TypeScript will try to infer a more specific data type when an if, else if, and else statements is used within the function.

Loading TypeScript...
Loading TypeScript...

We could fix the code above.

Loading TypeScript...

Arrow function

arrow functionparametersstring function
(param: string) => string
Loading TypeScript...

Defining functions with the arrow syntax is especially useful when working with functions as values. Suppose in the example above, we want to make it as easy as possible for a future developer to add support for new languages.

Loading TypeScript...

Another way to describe a function is as an arrow function. There is an important caveat to arrow functions that is discussed in classes.

Scope and closures

Every function has a scope of variables that are only accessible within that function. A closure is a function that has access to the variables from its surrounding scope, even after the surrounding function has finished executing.

Loading TypeScript...

Closures are commonly used to generate functions that operate on the arguments of the outer function.

Loading TypeScript...

Delay a function

The setTimeout function executes a given function after the specified delay (in milliseconds).

Setting timeouts is a synchronous action, which means that the program continues to perform instructions after setting the timeout. After a certain period of time, any ongoing execution will be interrupted to perform the sayGoodbye function.

Loading TypeScript...

Schedule a function

The global setInterval function schedules a certain function to be repeatedly executed at the given time interval.

Loading TypeScript...

The interval is defined in milliseconds, so 1000 is 1 second.

Was this page helpful?