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.
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.
A function can have multiple parameters, separated by a comma (,
).
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.
There are multiple ways to fix the program below so the race finishers are printed in the correct order.
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.
We could fix the code above.
Arrow function
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.
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.
Closures are commonly used to generate functions that operate on the arguments of the outer function.
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.
Schedule a function
The global setInterval
function schedules a certain function to be repeatedly executed at the given time interval.
The interval is defined in milliseconds, so 1000
is 1 second.