Arrow Functions की जानकारी
In this page:
const name = (param: type): returnType => {
return value;
};
const short = (param: type): returnType => expression;
Basic Arrow Functions
एक arrow function concise => syntax उपयोग करके एक function expression store करता है, उदाहरण के लिए const add = (a: number, b: number): number => a + b। यह typing purposes के लिए एक regular function जैसा behave करता है लेकिन काफी छोटे syntax के साथ।
उदाहरण: Basic Arrow Functions
const add = (a: number, b: number): number => a + b;
console.log(add(3, 4));
Implicit Returns
जब एक arrow function की body एक single expression हो, उस expression का result braces या एक explicit return keyword के बिना automatically return हो सकता है।
यह implicit-return form arrow functions के regular function syntax पर मिलने वाले सबसे बड़े ergonomic wins में से एक है।
उदाहरण: Implicit Returns
const square = (n: number) => n * n; // no braces, no explicit return
console.log(square(5));
Arrow Functions with Arrays
Arrow functions map, filter, और reduce जैसे array methods को pass किए गए inline callbacks के रूप में बहुत common हैं, exactly इसलिए क्योंकि उनका compact syntax एक short transformation को in place readable रखता है।
TypeScript इन cases में parameter types array के element type से infer करता है।
उदाहरण: Arrow Functions with Arrays
const nums = [1, 2, 3];
const doubled = nums.map((n) => n * 2);
console.log(doubled);
Arrow Functions with Multiple Parameters
Arrow functions exactly एक regular function declaration जैसे multiple typed parameters accept कर सकते हैं, उदाहरण के लिए (a: number, b: number) => a * b।
हर parameter पर type annotations identically काम करते हैं चाहे function arrow या traditional syntax उपयोग करे।
उदाहरण: Arrow Functions with Multiple Parameters
const multiply = (a: number, b: number) => a * b;
console.log(multiply(6, 7));
When to Use Arrow Functions
Short, concise operations और callbacks के लिए Arrow functions एक अच्छा default choice हैं, और वे this को उस तरह rebind नहीं करते जैसे regular functions करते हैं, जो classes और event handlers के अंदर काफी मायने रखता है।
Regular function declarations तब preferable रहते हैं जब आपको वह dynamic this binding या hoisting चाहिए।
उदाहरण: When to Use Arrow Functions
class Counter {
count = 0;
increment = () => {
this.count++; // arrow function keeps "this" bound to Counter
};
}
const c = new Counter();
c.increment();
console.log(c.count);
const square = (n: number) => { n * n }braces के साथ और बिनाreturnके लिखना, तो यहundefinedreturn करता है।- एक object literal को
() => { id: 1 }के रूप में return करना, जो एक block के रूप में पढ़ा जाता है, parentheses में wrap करने के बजाय। - एक arrow function में parameters को untyped छोड़ना जिसमें उन्हें infer करने का कोई context न हो।
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: