This page looks best with JavaScript enabled

Anonymous functions in Typescript

 ·   ·  ☕ 2 min read

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.

1
2
3
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.

1
2
3
4
5
6
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.

1
2
3
4
5
6
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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things