Function Basics in TypeScript
Learn how to declare functions, call functions, write reusable code, use parameters, and understand function declarations and function expressions in TypeScript.
What Is a Function?
A function groups statements together to perform a particular operation. Functions make programs easier to organize, reuse, maintain, and understand.
For example, in a student management application, we can create separate functions to display student details, calculate marks, and show course information.
- Functions help avoid repeated code.
- Functions can accept input values through parameters.
- Functions can return results to the calling code.
- Functions execute when they are called, rather than simply because they have been declared.
Function Workflow
Follow these steps to understand how a function is created and executed.
Step 1
Declare FunctionDefine the function and its statements.
Step 2
Pass InputProvide arguments when required.
Step 3
Execute FunctionRun the statements inside the function.
Step 4
Get ResultDisplay or use the result when required.
1. Function Declaration
A function declaration defines a function using the
function keyword, followed by a function
name, parentheses, and a block of code.
Syntax
function functionName(): void {
// Statements to execute
}
Example
function displayMessage(): void {
console.log("Welcome to TypeScript!");
}
Explanation
-
functionis the keyword used to declare the function. -
displayMessageis the function name. -
()contains the function parameters, if any. -
voidindicates that the function does not return a value. - The code inside the curly braces forms the function body.
2. Calling a Function
Calling a function means asking the program to execute the statements defined inside that function.
Example
function displayMessage(): void {
console.log("Hello, Student!");
}
displayMessage();
displayMessage();
Expected Output
Hello, Student!
Hello, Student!
Explanation
The function is called twice, so its message is printed
twice. We reuse the same function instead of writing the
same console.log() statement repeatedly.
3. Function with Parameters
Parameters allow a function to receive values from the code that calls it. TypeScript allows us to specify the type of each parameter.
Example
function greetStudent(name: string): void {
console.log("Welcome, " + name);
}
greetStudent("Rahul");
greetStudent("Priya");
Expected Output
Welcome, Rahul
Welcome, Priya
Explanation
-
name: stringdeclares a string parameter. -
"Rahul"and"Priya"are arguments passed to the function. - Each function call uses the supplied name to create a different message.
4. Function with a Return Value
A function can perform a calculation and return the result to the code that called it.
Example
function calculateSum(a: number, b: number): number {
return a + b;
}
let result: number = calculateSum(10, 20);
console.log("Sum:", result);
Expected Output
Sum: 30
Explanation
- The function receives two numeric parameters.
-
The
returnstatement returns their sum. -
The returned value is stored in
result. -
console.log()displays the result.
5. Function Expression
A function expression creates a function and assigns it to a variable. The function can then be called through that variable.
Example
const multiply = function (a: number, b: number): number {
return a * b;
};
console.log(multiply(4, 5));
Expected Output
20
Explanation
The function is assigned to the constant
multiply. We call it using
multiply(4, 5), and it returns
the product of the two numbers.
6. Function Declaration vs Function Expression
| Function Declaration | Function Expression |
|---|---|
Declared using the function keyword and a function name. |
A function assigned to a variable or constant. |
Example: function greet() { } |
Example: const greet = function() { }; |
| Function declarations are generally available before their position in the code because of hoisting. | A const or let variable cannot be accessed before its initialization. |
| Called using the declared function name. | Called using the variable or constant holding the function. |
7. Practical Example: CIIT Student Details
Let's create a function that displays a student's name and selected course.
Example
function displayStudentDetails(
studentName: string,
courseName: string
): void {
console.log("Student Name: " + studentName);
console.log("Course Name: " + courseName);
}
displayStudentDetails("Priya", "Dot Net Full Stack");
displayStudentDetails("Amit", "Java Full Stack");
Expected Output
Student Name: Priya
Course Name: Dot Net Full Stack
Student Name: Amit
Course Name: Java Full Stack
Explanation
The same function displays details for two different students. We pass the required name and course as arguments each time the function is called.
Common Mistakes
- Declaring a function but forgetting to call it.
- Passing an incorrect type of argument.
-
Forgetting to use
returnwhen a function must return a value. - Using an incorrect return type.
- Forgetting the closing curly brace or parentheses.
Practice Task
Write TypeScript functions to complete the following tasks.
- Create a function that displays your name.
- Create a function that accepts two numbers and displays their sum.
- Create a function that accepts a student's name and displays a welcome message.
- Create a function that returns the square of a number.
- Create a function that displays a student's name, course, and marks.
Summary
In this lesson, we learned how to declare and call functions, use parameters, return values, and write function expressions. Functions help us organize code into reusable blocks and make TypeScript programs easier to maintain.