Typescript anonymous functions

Author: Dawid Adach


Probably you already know that in JavaScript you can define functions like below:

// Named function
function add(x, y) {
    return x + y;

// Call named function

which are so called Named functions. You can also use Anonymous functions:

// Anonymous function
let myAdd = function(x, y) { return x + y; };

// You can call it like this 

// But definitely more common 
console.log ((function(x , y) {
  return x + y;

An anonymous function is a function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation.

One common use for anonymous functions is as arguments to other functions. Another common use is as a closure, for which see also the Closures chapter. Use as an argument to other functions:

setTimeout(function() {
}, 1000);

Or call it with parameter:

(function(message) {

So basically, you want to use Anonymous functions in all places where you have to use a function as an argument to other function or as a closure (we will learn about closures in next lessons).

In those cases you use the function only once, therefore you don't want to call it (use Named function) just to use it in a next line.

Anonymous functions might look confusing at the beginning, however, once you start using them you will find it very handy. But there is something else, another type the functions called arrow function which we will learn in a next lesson.

Next lesson

Spread the word:
Do you need help?: Use our support forum

About author

Dawid Adach
For more than 5 years Dawid was working as an IT Consultant specializing in SOA/EAI/ESB for banking domain. He was gaining experience working in countries like Netherlands, Belgium, Poland and India developing enterprise-class systems for the biggest companies within a domain. Since 2 years as a co-founder of mdbootstrap.com & brandflow.net is using and teaching others technologies like Angular, TypeScript, PHP, AJAX, Mongo, SQL, Hadoop Stack, Virtualization, Automation and many others...