Function declarations and function expressions

In the first chapter, we introduced the possibility of declaring functions with (named functions) or without (unnamed or anonymous functions) explicitly indicating their name, but we didn't mention that we were also using two different types of functions.

In the following example, the named function greetNamed is a function declaration, while greetUnnamed is a function expression. For now, please ignore the first two lines, which contain two console.log statements:

console.log(greetNamed("John")); // OK 
console.log(greetUnnamed("John")); // Error 
 
function greetNamed(name: string): string { 
    return `Hi! ${name}`; 
} 
 
let greetUnnamed = function(name: string): string { 
    return `Hi! ${name}`; 
}; 

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.