function <name> (<parameter name: type>, ...): <return type> {
<function body>
return <expression>;
}
Parameters
Return Type
Function Body
Return Statement
Example function:
let matchMaker = (personOne: string, personTwo: string): string => {
let couple: "Congratulations" + personOne + " " + personTwo;
return couple;
}
We can see the parts of the function in the following way:
Parameters: PersonOne and PersonTwo (both strings)
Return type: string
Function body: let couple: "Congratulations" + personOne + " " + personTwo;
Return statement: return couple;
Although in the example above, we only have one type in our parameters, you can have multiple
For example, we could modify the matchMaker function in the following way:
let matchMaker = (personOne: string, personTwo: string, areCompatable: boolean): string => {
let couple: "I'm not sure...";
if (areCompatable) {
let couple: "Congratulations " + personOne + " and " + personTwo;
}
return couple;
}
If we wanted to use the function, we would just call it using the function name followed by ( ) where we would include arguments to match the parameters the function requires.
Arguments are what we pass into parameters. If you are fuzzy on the difference between arguments and parameters, read here!
For example, calling matchMaker as it appears in the example above:
let result: matchMaker("Jim", "Pam", true);
// would return "Congratulations Jim and Pam" which would become result's value
Arguments don't have to be literals though, we can also (and much more commonly) pass variables into functions.
For example in the simple findSum function below:
let findSum = (x: number, y: number): number => {
let sum: number;
sum = x + y;
return sum;
}
A helpful way to think of a function is to compare it to a recipe: