In Typescript, functions are a fundamental building block for organising, and structuring code, and serve as reusable blocks of code.
There are two primary ways to define functions:
Traditional Function
Arrow Functions
Both have similar functionality but differ in syntax.
The traditional way to define a function in TypeScript is through a function declaration.
// Calculate sum of two numbers using Normal Function function addition(a: number, b: number): number { return a + b; } let additionResult: number = addition(10, 9); console.log(additionResult); // Output: 19 // Calculate multiplication of two numbers using Normal Function function multiply(a: number, b: number): number { return a * b; } let result: number = multiply(10, 9); console.log(result); // Output: 90
multiply is a function that takes two parameters (a and b), both of type number, and returns a number
// Calculate sum of two numbers using Arrow Function const addition = (a: number, b: number): number => a + b; let additionResult: number = addition(10, 9); console.log(additionResult); // Output: 19 // Calculate multiplication of two numbers using Arrow Function const multiply = (a: number, b: number): number => a * b; let result: number = multiply(10, 9); console.log(result); // Output: 90
Arrow functions provide a more concise syntax for writing functions, especially when the function body is a single expression.
multiply is an arrow function that takes two parameters (a and b), both of type number and returns a number. The arrow => signifies the beginning of the function body.
Function Declaration: Uses the function keyword.
Arrow Function: Uses the arrow (=>) syntax.
Function Declaration: Has its own binding.
Arrow Function: Inherits this binding from the enclosing scope. This behaviour is particularly useful in callbacks and event handlers.
Function Declaration: Creates a separate Function object.
Arrow Function: Does not create a separate Function object; instead, it inherits from the enclosing scope.
Function Declaration: Normal functions can be used as constructors when called with the new keyword
Arrow functions: can not be used as a constructor.
Arrow functions are generally used for shorter syntax and stateless functions.
Normal functions are more versatile and can be used in different scenarios.
Both functions have their benefits, and the choice between them depends on the specific use case of our code.