Comp 110 Calling Functions

Calling Functions

Function Calling Syntax

  •  Function calls in TypeScript have parenthesis () after the function's name
  •  Extra pieces of information required by the function definition are called parameters. The values provided in the function call are called arguments.

Here is an example of how we could call an arbitrary function f.

let f = (a: string, b: number, c: boolean): boolean => {   
 // function implementation would go here!
};
f("aardvark", 57, false);

Arguments vs. Parameters

Arguments get matched one-to-one with parametersThis means that each argument must be the same type as its corresponding parameter.

  • In the example above using function f,
    • Parameters : a: string, b: number, c: boolean
    • Arguments: "aardvark", 57, false
    • "aardvark" matches with a, 57 with b, false with c

Examples of an incorrect call of f:

f(false, "aardvark", 57);
//these arguments don't match the order of the parameters!
f(2, 1);
//too few arguments! This function requires three parameters.

Important note:

Function calls are expressions! They evaluate to a single value.

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!