Comp 110 Calling Functions

Calling Functions

Function Calling Syntax

If a function is like a written recipe, a function call is like opening the recipe book to follow the recipe.

  •  Function calls in TypeScript have parentheses () after the function's name.
  •  Arguments are the values provided in the function call. They are found within the parentheses.
  •  Arguments get matched one-to-one with parameters. This means that each argument must be the same type as its corresponding parameter. Read more on the difference between arguments and parameters here.

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 calls are expressions! They evaluate to a single value.
    • Just as (3+1) * 2 simplifies to (PEMDAS), myFunc("Hola", 1000) simplifies to 1000! 
    • NOther actions may also be taken in the function body so watch out - but ultimately the original function call can be replaced/simplified to the lone return value.
  • Parameters are usually used within the function-- but they aren't required to be. (In the myFunc function, parameter b is used, but parameter a is not. Though this isn't generally useful, it is allowed!)

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!