What functions are and why we need them
Function एक reusable block of code होता है। यानी एक ऐसा code जिसे हम बार-बार इस्तेमाल कर सकते हैं। अगर हमें कई बार एक जैसा काम करना हो, तो हर बार पूरा code लिखने के बजाय हम function बना लेते हैं। और जब हमें उस काम को करना होता है उस फंक्शन को कॉल कर लेते है | हमें फंक्शन की जरुरत क्यों है फंक्शन हमें Reusable Code देता है जिससे हमें सेम कोड को को बार -बार नहीं लिखा पड़ता है | Code छोटा और साफ रहता है तथा Maintenance आसान हो जाती है |
Function declaration syntax
जब हम function को सीधे function keyword से define करते हैं, उसे Function Declaration कहते हैं।
Function expression syntax
जब हम function को एक variable में store करते हैं, उसे Function Expression कहते हैं।
const functionName = function(parameters) {
// code
};
Example :
const add = function(a, b) {
return a + b;
};
console.log(add(4, 6));
Key differences between declaration and expression
Function Declaration
- function add(a,b){}
- सीधे define होता है|
- hoisting में काम करता है|
- पहले call कर सकते हैं|
Expression Declaration
- const add = function(a,b){}
- variable में store होता है|
- hoisting में नहीं चलता है |
- पहले define करना जरूरी होता है |
Basic idea of hoisting (very high level)
Hoisting का मतलब है कि JavaScript कुछ चीजों को code के ऊपर एक्सेस कर सकता है |
Function Declaration
hello();
function hello() {
console.log("Hi");
}
Declaration hoist हो जाता है, इसलिए उसे पहले call कर सकते हैं।
Function Expression
Expression hoist नहीं होता, इसलिए पहले define करना जरूरी है।
hello();
const hello = function() {
console.log("Hi");
};
ये एरर देगा |
When to use each type
Function Declaration उपयोग कब करें |
- function general purpose हो
- code के कई हिस्सों में use करना हो
function calculateTotal(a, b) {
return a + b;
}
Function Expression उपयोग कब करें
- function को variable की तरह use करना हो
- function को condition या callback में use करना हो
const multiply = function(a, b) {
return a * b;
};
Comparison table: declaration vs expression


