- JavaScript फ़ंक्शन declaration के लिए
function keyword, function expression, और arrow function सहित कई तरीके मौजूद हैं
- Function declaration पर hoisting लागू होती है, इसलिए इसे कोड में किसी भी जगह refer किया जा सकता है
- Arrow function का फायदा इसका संक्षिप्त syntax है, लेकिन this/arguments/super binding नहीं होती जैसी अहम भिन्नताएँ भी हैं
- Constructor function, generator, और method के लिए arrow function का उपयोग उपयुक्त नहीं है
- सरल callback या anonymous function के लिए arrow function ज़्यादा उपयुक्त है
Function Declarations, Function Expressions, and Arrow Functions
- JavaScript में फ़ंक्शन को function declaration (statement), function expression, और arrow function इन तीन तरीकों से define किया जा सकता है
- Function declaration
function isVowel(chr) { ... } की तरह नाम को सीधे bind करती है, और कोड में कहीं से भी refer की जा सकती है (hoisting)। Stack trace और debugging के दौरान फ़ंक्शन का नाम साफ़ दिखाई देता है
- Function expression
const takeWhile = function(predicate, arr) { ... } की तरह किसी variable में anonymous function assign करने का रूप है
- Function expression को अंदरूनी तौर पर नाम भी दिया जा सकता है, लेकिन वह नाम बाहरी scope में bind नहीं होता, और मुख्य रूप से stack trace में error tracking के काम आता है
Hoisting and Naming
- Function declaration को JavaScript engine hoist करता है, इसलिए declaration से पहले call करने पर भी यह काम करती है
- Anonymous function expression को variable assign होने के बाद ही call किया जा सकता है
- Debugging के लिए फ़ंक्शन को स्पष्ट नाम देना stack trace में फायदेमंद हो सकता है
Arrow Functions
Practical Example: this, constructor, और generator
- सामान्य function और arrow function के
this handling के अंतर का उदाहरण दिया गया है
- Object के अंदर method के रूप में इस्तेमाल करने पर सामान्य function का
this object को ही point करता है, जबकि arrow function का this undefined या बाहरी scope के this को point करता है
- Constructor function को arrow function से define करने पर TypeError आता है
- Generator function के लिए अनिवार्य रूप से
function* syntax का उपयोग करना पड़ता है
कौन-सा function syntax कब चुनना चाहिए?
- Generator (
yield का उपयोग) चाहिए → function* इस्तेमाल करें
- this का उपयोग करना है →
function keyword या class method इस्तेमाल करें
- Hoisting चाहिए या ऊपरी स्तर पर बेहतर readability चाहिए → function declaration इस्तेमाल करें
- अगर ऊपर की कोई शर्त लागू नहीं होती → arrow function से अधिक संक्षिप्त रूप में लिखना बेहतर है
निष्कर्ष
- JavaScript फ़ंक्शन का syntax उसके उपयोग,
this की ज़रूरत, और constructor/generator होने की आवश्यकता के आधार पर चुनना चाहिए
- रोज़मर्रा के callback/सरल function के लिए arrow function सबसे बेहतर है
- Object method/constructor/generator के लिए
function syntax का उपयोग करना चाहिए
- अगर hoisting या declaration order में flexibility चाहिए, तो function declaration अधिक फायदेमंद है
3 टिप्पणियां
मूल बातों जितना ही
prototypeकी मौजूदगी या गैर-मौजूदगी भी ...बनने वाले higher-order functions को refer करने का तरीका भी ...
const a = (a: () => null): (() => () => null) =>() => a
() => ❤️