Functions in TypeScript
Function Declarations vs. Function Expressions
TypeScript supports both function declarations and function expressions. Function declarations are hoisted, while function expressions are not.
- Function declarations can be called before they are defined due to hoisting.
- Function expressions assign a function to a variable, meaning they cannot be called before they are defined.
- Function expressions are useful when passing functions as arguments or assigning them dynamically.
// Function Declaration
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("Jake")); // Works
// Function Expression
const greet = function(name: string): string {
return `Hello, ${name}!`;
};
console.log(greet("Jake")); // Works