Arrow Functions in TypeScript
Learn how to write concise functions using arrow syntax, pass parameters, return values, and use arrow functions with arrays and callbacks in TypeScript.
=> arrow symbol to connect
the function parameters with its body.
What Is an Arrow Function?
An arrow function is a function expression introduced using the arrow syntax. It is commonly used for short operations, callback functions, and array methods.
-
Uses the
=>symbol. - Can accept zero, one, or multiple parameters.
-
Can return a value using an expression body or
an explicit
returnstatement. - Can be assigned to a variable or constant.
-
Uses lexical
this, which is useful when working with callbacks and object methods.
Arrow Function Workflow
Follow these steps to understand how an arrow function is defined and executed.
Step 1
Declare FunctionStore the arrow function in a variable.
Step 2
Pass ArgumentsSupply input values when needed.
Step 3
Execute FunctionRun the function body.
Step 4
Return ResultReceive the result when required.
1. Arrow Function Syntax
The arrow function syntax contains parameters,
the => symbol, and the function body.
Syntax
const functionName = (parameters) => {
// Function statements
};
Example
const welcome = (): void => {
console.log("Welcome to TypeScript!");
};
welcome();
Expected Output
Welcome to TypeScript!
Explanation
-
const welcomestores the function. -
()represents the parameter list. -
=>defines the arrow function. -
voidindicates that the function does not return a value.
2. Arrow Function with One Parameter
An arrow function can accept one parameter. When there is exactly one parameter and its type is provided through contextual typing or type inference, the parentheses may be omitted.
Example
const square = (number: number): number => {
return number * number;
};
console.log(square(5));
console.log(square(8));
Expected Output
25
64
Short Syntax
const double = (number: number): number => number * 2;
console.log(double(5));
Expected Output
10
When the body contains a single expression, its value
is returned automatically without writing
return.
3. Arrow Function with Multiple Parameters
Arrow functions can accept two or more parameters. Each parameter can have its own TypeScript type.
Example
const add = (a: number, b: number): number => {
return a + b;
};
console.log(add(10, 20));
console.log(add(50, 25));
Expected Output
30
75
Explanation
- The function accepts two numeric parameters.
-
The
returnstatement sends their sum back to the caller. - Each call can use different arguments.
4. Implicit and Explicit Return
Arrow functions can return values in two common ways: using an expression body for an implicit return, or using a block body with an explicit return statement.
A. Implicit Return
const multiply = (a: number, b: number): number => a * b;
console.log(multiply(4, 5));
Expected Output
20
B. Explicit Return
const multiplyNumbers = (a: number, b: number): number => {
return a * b;
};
console.log(multiplyNumbers(4, 5));
Expected Output
20
Difference
- An expression body returns its expression value automatically.
-
A block body uses curly braces and requires
returnwhen a value must be returned. - A block body without a return statement does not return the calculated expression automatically.
5. Arrow Functions with Arrays
Arrow functions are frequently used with array methods
such as map() to transform array elements.
Example
const numbers: number[] = [1, 2, 3, 4, 5];
const doubledNumbers: number[] = numbers.map(
(number: number): number => number * 2
);
console.log(doubledNumbers);
Expected Output
[ 2, 4, 6, 8, 10 ]
Explanation
-
The
numbersarray contains five values. -
The
map()method applies the arrow function to each element. - The arrow function returns each number multiplied by 2, creating a new array.
6. Arrow Functions with Filter
The filter() method uses a callback
function to select elements that satisfy a condition.
Example
const numbers: number[] = [10, 15, 20, 25, 30];
const evenNumbers: number[] = numbers.filter(
(number: number): boolean => number % 2 === 0
);
console.log(evenNumbers);
Expected Output
[ 10, 20, 30 ]
Explanation
The arrow function checks whether each number is divisible by 2. The filter method returns a new array containing only the numbers that satisfy the condition.
7. Arrow Functions and the This Keyword
Arrow functions do not create their own
this binding. They use the
this value from the surrounding
lexical scope.
Example
const student = {
name: "Rahul",
showNameLater(): void {
const display = (): void => {
console.log(this.name);
};
display();
}
};
student.showNameLater();
Expected Output
Rahul
Explanation
The arrow function uses the this value
from showNameLater(). In this call,
that value refers to the student object.
8. Function Declaration vs Arrow Function
| Function Declaration | Arrow Function |
|---|---|
Uses the function keyword. |
Uses the => symbol. |
Has its own this binding. |
Uses lexical this. |
| Can be called before its declaration in common cases because of function hoisting. | A function assigned to a const or let cannot be called before initialization. |
| Useful for named reusable functions. | Commonly used for callbacks and concise expressions. |
function add(a, b) { return a + b; } |
const add = (a, b) => a + b; |
9. Practical Example: CIIT Student Results
Let's use arrow functions to calculate a student's percentage and check whether the student has passed.
Example
const calculatePercentage = (
obtainedMarks: number,
totalMarks: number
): number => (obtainedMarks / totalMarks) * 100;
const checkResult = (percentage: number): string =>
percentage >= 40 ? "Pass" : "Fail";
const percentage: number = calculatePercentage(420, 500);
console.log("Percentage:", percentage + "%");
console.log("Result:", checkResult(percentage));
Expected Output
Percentage: 84%
Result: Pass
Explanation
-
calculatePercentagecalculates and returns the percentage. -
checkResultuses a ternary expression to return either Pass or Fail. - Both functions use arrow syntax and explicit parameter and return types.
Common Mistakes
-
Using
=instead of=>between parameters and the body. -
Forgetting
returninside a block body when a value is required. - Returning a value that does not match the declared return type.
-
Assuming arrow functions have their own
thisbinding. - Omitting parentheses around multiple parameters.
Practice Task
Write TypeScript arrow functions to complete the following tasks.
- Create an arrow function that returns the square of a number.
- Create an arrow function that accepts two numbers and returns their maximum value.
-
Use
map()to multiply every number in an array by 3. -
Use
filter()to select numbers greater than 50 from an array. - Create an arrow function that calculates a student's percentage and returns Pass or Fail.
Summary
In this lesson, we learned how to define arrow functions, use parameters and return types, write implicit and explicit returns, work with array methods, and understand lexical this. Arrow functions provide concise syntax and are especially useful for callbacks and array operations.