Comp 110 Function Syntax and Parts

Syntax

Here's the syntax for writing functions:

let <functionName> = (<parameter>: <type>, <anotherParameter>: <type>): <returnType> => {
   <function body statements>
};

Breaking it all down

Name

Just like all variables, functions have names. We establish a function's name after the let keyword.

Parameters

Parameters are what the function takes in. They go inside the parentheses ( ) following the equals sign, and we must give them types. 

Parameters are local to the function definition, so they can only be used within the function. A function can have as many parameters as we want, we just have to separate them with commas. 

If there are no parameters, we still need the parentheses, but we just leave them empty.

Return Type

The return type of a function indicates the type of data the function will return. The function must return a variable or expression that simplifies to the same type as the return type.

Function Body

Everything within the function's curly braces { } makes up the function body. Statements in the body of the function will only be executed when the function is called.

Note

After the closing curly brace } of the following function, there's a semicolon ;. Since we are defining the function and assigning it to a variable, we must end this statement with a semicolon.

Example

Here's an example function definition:

let happyBirthday = (name: string, age: number): number => {
   print("Happy Birthday " + name);
   age = age + 1;
   return age;
};
happyBirthday( "Kris", 109);
//prints Happy Birthday Kris
//age is NOT printed but is updated to 110

The example happyBirthday function above takes in a string (the name parameter) and a number (the age parameter). It prints the string "Happy Birthday " plus the name the user input then changes the value of the age variable by assigning it the value of the input age plus one. The function then returns the value stored in the updated age variable.