TypeScript Anonymous Functions

TypeScript Anonymous Functions are functions that are not bound to an identifier i.e., anonymous functions do not have name of the function.

Anonymous functions are used as inline functions. These are used when the function is used only once and does not require a name. The best example is a callback function.

Syntax of Anonymous Function in TypeScript

var varName = function( [arguments] ) { 
    // function body          
}
  • var is the keyword
  • varName is the name of the variable in which function is stored
  • function (is a keyword) is an operator that creates a TypeScript Function during runtime
  • arguments are optional variables that could be declared for the anonymous function
  • function body can contain multiple lines of code
ADVERTISEMENT

Example 1 – Anonymous function with arguments

In the following example, an anonymous function is defined and assigned to a variable named result.

example.ts

var result = function(a:number, b:number) { 
    return a+b
}

var c = result(12,2) // c = 14

When the above code is transpiled, following JavaScript code is generated.

example.js

var result = function (a, b) {
    return a + b;
};
var c = result(12, 2); // c = 14

Example 2 – Anonymous function with no arguments

example.ts

var displayMessage = function () {
    console.log("Hello User!")
}

displayMessage()

Transpiled JavaScript code would be as shown below.

example.js

var displayMessage = function () {
    console.log("Hello User!");
};
displayMessage();

Output

Hello User!

Conclusion

In this TypeScript TutorialTypeScript Anonymous Functions, we have learnt how to define an anonymous function with and without parameters using the help of detailed examples.