Comp 110 Functions

Defining a Function

function <name> (<parameter name: type>, ...): <return type> {
     <function body>

Parts of a Function


  • located within the () of a function definition
  • refer to variables that the user passes in when the function is called
  • are local to the function definition (can only be used inside the { } of the function definition)

Return Type

  • can be number, boolean, string, or void
  • function must return an object or expression that simplifies to the same type as the return type
  • void functions do not contain a return statement

Function Body

  • located within the { } of the function
  • gives 'functionality' to the function
  • code will only be executed when the function is called elsewhere in the code
  • if not void, MUST contain a return statement

Return Statement

  • type must match the return type of its function
  • every function that returns a value must have at least one return statement
  • as soon as any return statement is reached the function call is complete
    • even if within an if-then-else block!
return <expression>;


function findSum(x: number, y: number): number {
     let sum: number;
     sum = x + y;
     return sum;

In the function above, 'findSum' is the name of the function. 'findSum' has two parameters that are both of type 'number' represented by variables 'x' and 'y'. By calling 'findSum,' a number object or expression will be returned