Arrow functions are concise function expressions that use the => syntax. They provide a shorter way to write functions while preserving the lexical this context.

- Provide a shorter syntax for defining functions.
- Preserve the lexical this context.
- Commonly used for callbacks, array methods, and one-line functions.
Syntax:
(param1: type, param2: type): returnType => expression;
(): returnType => expression;
const greet = (name: string): string => `Hello, ${name}!`;
console.log(greet("Alen"));
Output:
Hello, Alen!- greet is an arrow function that accepts a string.
- It returns a greeting message.
- The return type is explicitly defined as string.
Arrow Function in a Class
Arrow functions in classes preserve the lexical this context, making them useful for class properties and callbacks.
class Calculator {
add = (a: number, b: number): number => a + b;
}
const calc = new Calculator();
console.log(calc.add(5, 3));
Output:
8- add is defined as an arrow function.
- It preserves the lexical this context.
- Calling add() returns the sum of the two numbers.
Arrow Function with Array Methods
Arrow functions provide a concise way to process array elements using methods like map(), filter(), and reduce().
const numbers = [1, 2, 3, 4, 5];
const squared = numbers.map(n => n * n);
console.log(squared);
Output:
[1, 4, 9, 16, 25]- map() applies the arrow function to each array element.
- Each number is squared.
- The result is stored in a new array.
Arrow Function as a Callback
Arrow functions are commonly used as callbacks because they provide concise syntax and preserve the lexical this context.
setTimeout(() => {
console.log("This message is displayed after 1 second.");
}, 1000);
Output:
This message is displayed after 1 second.- The arrow function is passed as a callback to setTimeout().
- It executes after a one-second delay.
- Arrow functions are commonly used for callbacks because of their concise syntax.
Best Practices
- Use arrow functions for callbacks and array methods.
- Use regular methods when dynamic this binding is required.
- Wrap returned object literals in parentheses.
- Use arrow functions to preserve the lexical this context.