JS हायर ऑर्डर फंक्शन्स
function higherOrder(callback) {
return callback(value);
}
array.map(fn);
array.filter(fn);
array.reduce(fn, initial);
Higher Order Function क्या है
एक higher-order function या तो किसी दूसरे function को argument के रूप में स्वीकार करता है, एक function return करता है, या दोनों — functions को साधारण values की तरह मानते हुए जिन्हें आप किसी भी दूसरे data की तरह इधर-उधर पास कर सकते हैं।
उदाहरण: What Is a Higher Order Function
function repeat(n, action) {
for (let i = 0; i < n; i++) action(i);
}
repeat(3, console.log); // passing a function as an argument
map
Array.prototype.map() एक callback लेता है और एक नई array return करता है जिसमें हर element उस callback को संबंधित original element पर लागू करने का result होता है, original array को अनबदला छोड़ते हुए।
उदाहरण: map
const nums = [1, 2, 3];
console.log(nums.map(n => n * 2));
filter
Array.prototype.filter() एक callback लेता है जो हर element के लिए true या false return करता है और सिर्फ उन elements वाली एक नई array return करता है जहाँ callback ने true return किया।
उदाहरण: filter
const nums = [1, 2, 3, 4];
console.log(nums.filter(n => n % 2 === 0));
reduce
Array.prototype.reduce() एक callback और एक initial value लेता है, फिर बार-बार हर element को एक single accumulated result में मिलाता है — यह sums, groupings, या किसी list से कोई भी single output बनाने के लिए उपयोगी है।
उदाहरण: reduce
const nums = [1, 2, 3, 4];
console.log(nums.reduce((sum, n) => sum + n, 0));
Higher Order Methods को Combine करना
चूंकि map, filter, और reduce सभी नई arrays या values return करते हैं, आप हर transformation step के लिए अलग loops लिखने के बजाय इन्हें एक single readable pipeline में एक साथ chain कर सकते हैं।
उदाहरण: Combining Higher Order Methods
// Declare the constant `nums`, set to `[1, 2, 3, 4, 5, 6]`
// Declare the constant `nums`, set to `[1, 2, 3, 4, 5, 6]`
const nums = [1, 2, 3, 4, 5, 6];
// Declare the constant `result`, set to `nums.filter(n => n % 2 === 0).map(n => n * 10).reduce((sum, n) => sum + n, 0)`
// Declare the constant `result`, set to `nums.filter(n => n % 2 === 0).map(n => n * 10).reduce((sum, n) => sum + n, 0)`
const result = nums.filter(n => n % 2 === 0).map(n => n * 10).reduce((sum, n) => sum + n, 0);
// Print `result` to the console
// Print `result` to the console
console.log(result);
map()के अंदर कोई valuereturnकरना भूल जाना, इसलिए नई arrayundefinedसे भर जाती है।- सिर्फ side effects के लिए
map()इस्तेमाल करना, जबकि उसके लिएforEach()intended है। - यह उम्मीद करना कि किसी empty array पर
reduce()बिना initial value के काम करेगा, जोTypeErrorthrow करता है।
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: