Interview question
What is the difference between function declaration and function expression? Function declaration और function expression में क्या अंतर है?
Answer
| Aspect | Declaration | Expression |
|---|---|---|
| Syntax | function name() { } | const name = function() { } |
| Hoisting | Fully hoisted - can call before declaration | Not hoisted - throws error if called before |
| Named | Always named | Can be anonymous or named |
| When it runs | At parse time | At runtime |
// Function Declaration - hoisted
console.log(greet1()); // 'Hello' - works!
function greet1() {
return 'Hello';
}
// Function Expression - not hoisted
console.log(greet2()); // ReferenceError: Cannot access 'greet2' before initialization
const greet2 = function() {
return 'Hello';
};
// Named function expression
const factorial = function fact(n) {
return n <= 1 ? 1 : n * fact(n - 1);
};Interview tip: Explain that hoisting means function declarations are moved to the top of their scope at parse time, but function expressions are only initialized when the code runs. This is a common source of bugs.
| Aspect | Declaration | Expression |
|---|---|---|
| Syntax | function name() { } | const name = function() { } |
| Hoisting | Fully hoisted - पहले call कर सकते हैं | Hoisted नहीं - error मिलेगी |
| Named | हमेशा named | Anonymous या named |
| Execution | Parse time पर | Runtime पर |
// Declaration - hoisted
console.log(greet1()); // 'Hello' - काम करता है!
function greet1() {
return 'Hello';
}
// Expression - hoisted नहीं
console.log(greet2()); // ReferenceError
const greet2 = function() {
return 'Hello';
};
// Named function expression
const factorial = function fact(n) {
return n <= 1 ? 1 : n * fact(n - 1);
};इंटरव्यू टिप: समझाएं hoisting का मतलब function declarations को scope के top पर move किया जाता है, पर function expressions सिर्फ तब initialize होते हैं जब code run हो।
Was this answer clear?