Hello, function builder! In Module Three, you learned about interfaces and types. Now it is time to learn about functions β the building blocks of any program.
Functions are reusable blocks of code that perform a specific task. They help you organise your code, avoid repetition, and make your programs more powerful. In TypeScript, functions can have types for parameters and return values.
In this module, you will learn how to write functions with type annotations, use optional and default parameters, and work with arrow functions.
Let's start building functions with TypeScript!
By the end of this module, you will be able to:
In Lagos, a developer named Olu was building a calculator app. He had to write the same code many times to add, subtract, multiply, and divide numbers.
His mentor said, "Olu, you should use functions β they are reusable blocks of code. Write a function for each operation."
Olu wrote a function for addition, one for subtraction, and so on. He could now use them again and again. He said, "Functions saved me so much time!"
Definition: A function is a block of code that performs a specific task.
Why is it important? Functions help you reuse code and keep things organised.
Simple explanation: A function is like a recipe β you can use it whenever you want.
Real-life example: A recipe for making jollof rice.
School example: A formula for calculating grades.
Home example: A routine for cleaning the house.
Nigerian example: A function for calculating prices with VAT.
function greet() {
console.log("Hello!");
}
Mini summary: Functions are reusable blocks of code.
Definition: Parameters are values that you pass to a function for it to use.
Why is it important? They make functions flexible and reusable.
Simple explanation: Parameters are like ingredients in a recipe.
Real-life example: A function that greets a person by name.
School example: A function that calculates a student's grade.
Home example: A function that calculates the cost of groceries.
Nigerian example: A function that calculates tax.
function greet(name: string) {
console.log(`Hello ${name}!`);
}
Mini summary: Parameters let you pass data to functions.
Definition: A return type is the type of value that a function returns.
Why is it important? It tells you what kind of value the function produces.
Simple explanation: It's like what you get after following a recipe.
Real-life example: A function that returns a number.
School example: A function that returns a grade.
Home example: A function that returns the total cost.
Nigerian example: A function that returns the price with tax.
function add(a: number, b: number): number {
return a + b;
}
Mini summary: Return types tell you what a function produces.
Definition: Optional parameters are parameters that are not required.
Why is it important? They give you flexibility.
Simple explanation: You can call the function with or without the parameter.
Real-life example: A function that greets a person, but you can skip the name.
School example: A function that grades a student, but you can skip the subject.
Home example: A function that calculates cost, but you can skip the tax.
Nigerian example: A function that calculates price, with an optional discount.
function greet(name?: string) {
if (name) {
console.log(`Hello ${name}!`);
} else {
console.log("Hello!");
}
}
Mini summary: Optional parameters are not required.
Definition: Default parameters have a default value if no value is provided.
Why is it important? They ensure that a function always has a value.
Simple explanation: You provide a fallback value.
Real-life example: A function that greets a person, with a default name.
School example: A function that calculates grades, with a default subject.
Home example: A function that calculates cost, with a default tax rate.
Nigerian example: A function that calculates price, with a default discount.
function greet(name: string = "Guest") {
console.log(`Hello ${name}!`);
}
Mini summary: Default parameters have a fallback value.
Definition: Arrow functions are a shorter way to write functions.
Why is it important? They make your code more concise.
Simple explanation: It's like a shortcut for writing functions.
Real-life example: const greet = (name: string) => console.log(`Hello ${name}!`);
School example: const add = (a: number, b: number) => a + b;
Home example: const multiply = (a: number, b: number) => a * b;
Nigerian example: const tax = (price: number) => price * 0.075;
const add = (a: number, b: number): number => {
return a + b;
};
Mini summary: Arrow functions are a shorter way to write functions.
Definition: Function types describe the shape of a function β its parameters and return type.
Why is it important? They help you use functions as values.
Simple explanation: You can assign functions to variables.
Real-life example: let add: (a: number, b: number) => number;
School example: let grade: (score: number) => string;
Home example: let cost: (price: number, tax: number) => number;
Nigerian example: let tax: (price: number) => number;
let add: (a: number, b: number) => number; add = (a, b) => a + b;
Mini summary: Function types describe the shape of functions.
Definition: Void functions do not return anything.
Why is it important? They are used for actions, not calculations.
Simple explanation: They perform a task but don't give back a value.
Real-life example: A function that prints a message.
School example: A function that displays a grade.
Home example: A function that shows a cost.
Nigerian example: A function that logs a transaction.
function greet(name: string): void {
console.log(`Hello ${name}!`);
}
Mini summary: Void functions do not return a value.
Definition: Rest parameters allow a function to accept any number of arguments.
Why is it important? They are useful when you don't know how many arguments you'll get.
Simple explanation: You can pass as many values as you want.
Real-life example: A function that adds any number of numbers.
School example: A function that averages any number of scores.
Home example: A function that calculates total cost of multiple items.
Nigerian example: A function that calculates total price with tax.
function sum(...numbers: number[]): number {
return numbers.reduce((acc, cur) => acc + cur, 0);
}
Mini summary: Rest parameters accept any number of arguments.
Definition: Function overloads allow a function to have different parameter types.
Why is it important? They provide flexibility.
Simple explanation: You can call the same function with different types.
Real-life example: A function that can accept a string or a number.
School example: A function that can accept a name or an ID.
Home example: A function that can accept a price or a discount.
Nigerian example: A function that can accept a product name or ID.
function greet(name: string): void;
function greet(age: number): void;
function greet(value: any): void {
console.log(value);
}
Mini summary: Function overloads allow different parameter types.
Definition: You can use interfaces to describe functions.
Why is it important? It makes your code more organised.
Simple explanation: You define a function shape with an interface.
Real-life example: interface Add { (a: number, b: number): number; }
School example: interface Grade { (score: number): string; }
Home example: interface Cost { (price: number, tax: number): number; }
Nigerian example: interface Tax { (price: number): number; }
interface Add {
(a: number, b: number): number;
}
let add: Add = (a, b) => a + b;
Mini summary: Interfaces can describe functions.
Definition: Common mistakes are errors that beginners often make with functions.
Why is it important? Avoiding them saves time and frustration.
Simple explanation: Don't forget to return a value.
Real-life example: Forgetting to return a number from a function.
School example: Forgetting to return a grade.
Home example: Forgetting to return a total cost.
Nigerian example: Forgetting to return a price.
function add(a: number, b: number): number {
// Missing return statement
}
Mini summary: Always return a value if the function expects one.
Definition: Best practices are the recommended ways to write functions.
Why is it important? They make your code clean and safe.
Simple explanation: Use types for parameters and return values.
Real-life example: function add(a: number, b: number): number { return a + b; }
School example: function getGrade(score: number): string { ... }
Home example: function getCost(price: number, tax: number): number { ... }
Nigerian example: function calculateTax(price: number): number { ... }
function add(a: number, b: number): number {
return a + b;
}
Mini summary: Use types for parameters and return values.
Definition: Functions are not just for code β they are everywhere in life.
Why is it important? It shows that functions are natural and easy to understand.
Simple explanation: You use functions every day β like recipes and routines.
Real-life example: A recipe is like a function.
School example: A formula is like a function.
Home example: A cleaning routine is like a function.
Nigerian example: A cooking process is like a function.
Functions are like recipes β they give you instructions.
Mini summary: Functions are natural and easy to understand.
Definition: You are now a function master β you understand functions in TypeScript.
Why is it important? You can now write reusable, organised code.
Simple explanation: You have mastered functions.
Real-life example: You can now write functions for any task.
School example: You can use functions in school projects.
Home example: You can practice at home.
Nigerian example: You can build apps with functions in Nigeria.
Function Master Checklist: - Understands parameters and return types - Uses optional and default parameters - Writes arrow functions - Knows function types - Uses rest parameters
Mini summary: You are now a function master!
| Word | Simple Definition |
|---|---|
| Function | A reusable block of code. |
| Parameter | Input to a function. |
| Return | The output of a function. |
| Optional | Not required. |
| Default | A fallback value. |
| Arrow | A shorter function syntax. |
| Void | No return value. |
| Rest | Any number of arguments. |
| Overload | Different parameter types. |
| Interface | Describes a function shape. |
function add(a: number, b: number): number {
return a + b;
}
const add = (a: number, b: number): number => a + b;
+-----------------------+-----------------------+
| Function | Arrow Function |
+-----------------------+-----------------------+
| function add(a,b){...}| const add=(a,b)=>... |
| Has its own 'this' | No own 'this' |
| Can be used as method | Best for callbacks |
| More verbose | More concise |
| Traditional | Modern |
+-----------------------+-----------------------+
| Type | Description | Example |
|---|---|---|
| Regular | Standard function | function add(a: number, b: number): number |
| Arrow | Concise function | const add = (a: number, b: number): number => a + b |
| Void | No return value | function greet(name: string): void |
| Rest | Any number of arguments | function sum(...numbers: number[]): number |
| Type | Description | Example |
|---|---|---|
| Required | Must be provided | function greet(name: string) |
| Optional | May be omitted | function greet(name?: string) |
| Default | Has a fallback value | function greet(name: string = "Guest") |
| Rest | Any number of arguments | function sum(...numbers: number[]) |
(Included after each lesson above β review them!)
In this module, you learned about functions in TypeScript. You discovered how to write functions with parameters and return types. You also learned about optional parameters, default parameters, arrow functions, and rest parameters. You are now a function master. In the next module, you will learn about classes and objects. Congratulations on completing Module Four!
Match the term with its definition.
| Term | Definition |
|---|---|
| 1. Function | A. Reusable block of code |
| 2. Parameter | B. Input to a function |
| 3. Return | C. Output of a function |
| 4. Optional | D. Not required |
| 5. Default | E. Fallback value |
Answers: 1-A, 2-B, 3-C, 4-D, 5-E
βFunction Designβ
In groups, design functions for a real-world scenario (like a calculator or a store). Share your functions with the class.
βMy Functionsβ
Write functions for a business scenario (like a store or a school). Use parameters and return types. Share your code with the class.
βFunction Libraryβ
Create a library of functions for a business. Include functions for calculations, greetings, and validation. Present your library to the class.
βWrite TypeScript Functionsβ
Write a TypeScript program with multiple functions. Include parameters, return types, optional parameters, and arrow functions. Compile and run it. Share your code and output.
βFunction Challengeβ
Create a complex function that uses optional parameters, default parameters, and rest parameters. Share your solution with the class.
(Answers to fill-in-the-blank, true/false, and multiple choice are provided within those sections.)
In Module Five, you will learn about classes and objects. To prepare:
Get ready to learn about classes!
End of Module Four Β· You are now a function master!