InterviewSolution
| 1. |
Explain the arrow function syntax in TypeScript. |
|
Answer» Arrow functions provide a SHORT and convenient syntax to DECLARE functions. They are also called LAMBDAS in other programming languages. Consider a regular function that adds two numbers and returns a number. function add(x: number, y: number): number {let sum = x + y;return sum;}Using arrow functions syntax, the same function can be defined as: let add = (x: number, y: number): number => {let sum = x + y;return sum;}You can further simplify the syntax by GETTING rid of the brackets and the return STATEMENT. This is allowed when the function body consists of only one statement. For example, if we remove the temporary sum variable, we can rewrite the above function as: let add = (x: number, y: number): number => x + y;Arrow functions are often used to create anonymous callback functions in TypeScript. Consider the example below that loops over and filters an array of numbers and returns an array containing multiples of five. The filter function takes an arrow function. let numbers = [3, 5, 9, 15, 34, 35];let fiveMultiples = numbers.filter(num => (num % 5) == 0);console.log(fiveMultiples); // [5, 15, 35] |
|