TypeScript supports anonymous functions and arrow functions, which are more concise ways to write functions.
If you want to learn more about What Lambda Functions Are
check out the Introduction to Programming Course read more
Anonymous Functions
Anonymous functions are functions without a name, commonly used as arguments to other functions.
const greet = function(name: string): void {
console.log(`Hello ${name}.`);
};
These functions (as their name suggests) have no assigned name and are used in a variety of contexts. Especially when a temporary or short-lived function is needed.
Arrow Functions
Arrow functions are a compact syntax for defining functions in JavaScript and TypeScript. They are characterized by using the =>
syntax and have several advantages over traditional functions, especially in terms of handling this
.
Arrow functions allow for more concise and readable function writing, especially when dealing with short or single-line functions.
The basic syntax of an arrow function is as follows:
(param1, param2, ..., paramN) => {
// function body
}
For example,
const greet = (name: string): void => {
console.log(`Hello ${name}.`);
};
For functions with a single parameter, parentheses can be omitted:
param => {
// function body
}
If the function consists of a single expression, the curly braces and the return
keyword can be omitted:
(param1, param2) => param1 + param2
Arrow functions are particularly useful in contexts where it is necessary to preserve the this
context of the enclosing function, as they use the this
context from the environment in which they were created.