Anonymous functions in Typescript

Let’s talk anonymous functions and make them, well, “not anonymous”.

Anonymous functions are just functions without names. If you have been following this blog, or have written some Javascript - you surely would have come across them.

Anonymous functions are just function expressions. Let’s see a quick example.

The following code block has a ‘named’ function.

function getSum(x: number, y: number): number {
  return x + y;
}

We can rewrite the same as an anonymous function and get the same end result.

const getASum = function(x: number, y: number) {
  return x + y;
};

console.log(getASum(1, 2));
// 3

As it was in Javascript, the function declaration in anonymous functions get compiled only when the runtime engine gets to the particular statement. In other words, anonymous functions are not hoisted.

“Normal” functions get parsed at the compile time, regardless of whether they are used or unused.

Wot? But, this is similar arrow functions?

Yes, and no.

Arrow functions (or lambda functions) help us further the idea of Javascript - “every function is an object”. They allow us to pass around functions, and build incrementally complicated code that no one can understand.

Here’s an arrow function.

const getRSum = (x: number, y: number) => {
  return x + y;
};

console.log(getRSum(1, 2));
// 3

The only three differences -

  • arrow functions can be named while anonymous functions wish to stay unnamed
  • more importantly: anonymous functions have their own this context and arguments object while arrow functions inherit from parent/scope
  • arrow functions cannot be called with new keyword

For all practical purposes I just use arrow functions and call it a day.

comments powered by Disqus