Summary - Arrow functions
- TypeScript course
- Beginner
- Lesson 50/89
- 4 min
Write a list filtering program with arrow functions.
Summary - Arrow functions
Arrow functions provide concise syntax, lexical this, and use as a type. Together they enable clean and safe code in filtering, mapping, and callback-based operations.
let sayilar = [1, 2, 3, 4, 5];
let buyukler = sayilar.filter((n: number) => n > 3);
// buyukler: [4, 5]Arrow functions make functional programming patterns easy in TypeScript.
Practice List filtering program
Declare an array named sayilar with value [1, 2, 3, 4, 5]. Use the .filter() method with an arrow function to filter numbers greater than 3. Print the first element of the filtered array with console.log.
Starter code
// sayilar dizisini tanımla: [1, 2, 3, 4, 5]
// filter ve arrow function ile 3'ten büyük olanları filtrele
// filtrelenmiş dizinin ilk öğesini yazdırSample solution
let sayilar = [1, 2, 3, 4, 5];
let buyukler = sayilar.filter((n: number) => n > 3);
console.log(buyukler[0]);Expected output
4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why is an arrow function preferred in a callback inside a method?
- Because it preserves the enclosing method's this Correct answer
- Because it is faster
- Because it can take more parameters
- Because it prevents errors
Explanation: An arrow function takes <code>this</code> lexically; in a callback inside a method, <code>this</code> is not lost. In a regular function, <code>this</code> changes by call site and is lost.
2 Add the filter threshold value
let sayilar = [1, 2, 3, 4, 5];
let buyukler = sayilar.filter((n: number) => n > ____);
let sayilar = [1, 2, 3, 4, 5];
let buyukler = sayilar.filter((n: number) => n > 2);
Explanation: To filter numbers greater than 2, the threshold must be <code>2</code>; <code>n > 2</code> gives [3, 4, 5]. <code>1</code> gives [2,3,4,5], <code>5</code> gives an empty array, and <code>0</code> gives the whole array.
3 Arrow functions summary
| Term | Meaning |
|---|---|
(a, b) => a + b |
Short function syntax |
Arrow this |
From lexical scope |
(x: number) => number |
Function type |
Arrow callback |
Use in filtering and mapping |