Search⌘ K

Named and Anonymous Functions

Explore the differences between named and anonymous functions in TypeScript, understand how to apply types to function arguments and return values, and learn to use the concise arrow function syntax. This lesson helps you grasp function declarations, expressions, and handling return types for effective TypeScript coding.

Expressions and declarations

JavaScript, and therefore TypeScript, have many ways to define functions. At a high level, functions can be divided into function declarations and function expressions. A function declaration is when a function is defined by not assigning the function to a variable. e.g.

function myFunction() ...

A function expression is a function assigned to a variable. e.g.

const f = function() ...

The function expression example leads to the creation of anonymous functions where a pointer to a function exists but the function is nameless.

TypeScript 3.3.4
// Named Function
function functionName1(){}
functionName1(); // Invocation
// Anonymous Function 1
const pointerToFunction1 = function(){}
pointerToFunction1(); // Invocation
// Anonymous Function 2 + Invocation A.K.A. IIFE
(function(){})();

Function’s arguments

TypeScript types are used for function arguments. Types at the level of arguments are valid for named ...