Function Calling Syntax
If a function is like a written recipe, a function call is like opening the recipe book to follow the recipe.
Here is an example function:
// Function definition: let myFunc = (a: string, b: number): number => { return b; }; // Function call: myFunc("Hola", 1000);
The parameters are required in the order they are specified, and all parameters must be given an argument. Examples of incorrect calls to myFunc:
myFunc(1000, "Hola"); // Incorrect order of arguments myFunc(2, 1); // Incorrect types of arguments myFunc(1000); // Too few arguments myFunc(1, "Hi", "Hola"); // Too many arguments
Important notes:
Function call tracing example:
let addOne = (n: number): number => { // (5) return n + 1; (6) }; let main = async () => { // (2) let initial = 5; // (3) let increment = addOne(initial); // (4), (7) print(increment); // (8) }; main(); // (1)
//1 The call to main starts the program and we jump into the main function.
//2 The code inside the main function definition begins executing.
//3 initial is declared and assigned the value of 5.
//4 increment is then assigned the value of the function call addOne(initial). This is valid because function calls are also expressions and can evaluate to a single value. However, the return type of the function must match the type of the variable.
//5 We then jump into the addOne function. The parameter, n, takes the value of the argument passed to the function, initial.
//6 The value of the expression n + 1 is returned. In this case, it's 6.
//7 The result of the call addOne(initial) is stored in increment.
//8 The value of increment is printed out and the program is done executing!