What are arrow functions and how do they differ from regular functions? Arrow functions क्या हैं और regular functions से कैसे अलग हैं?
Arrow functions (=>) are a concise syntax for writing functions introduced in ES6. They differ in syntax, this binding, and use cases.
| Feature | Regular Function | Arrow Function |
|---|---|---|
| Syntax | function name() { } | (params) => { } |
| this binding | Dynamic - depends on how called | Lexical - inherited from parent scope |
| arguments object | Yes, available | No, use rest parameters instead |
| Can be constructor | Yes, with new keyword | No, cannot use new |
| Implicit return | No, need return keyword | Yes, for single expression |
// Regular function
const add1 = function(a, b) {
return a + b;
};
// Arrow function - explicit return
const add2 = (a, b) => {
return a + b;
};
// Arrow function - implicit return (single expression)
const add3 = (a, b) => a + b;
// Single parameter (parens optional)
const double = x => x * 2;
// Arrow functions and this
const obj = {
name: 'John',
regular: function() {
console.log(this.name); // 'John' - this refers to obj
},
arrow: () => {
console.log(this); // Window/global - lexical this!
}
};
// Arrow functions have no arguments object
const test = () => {
console.log(arguments); // ReferenceError
};Interview tip: The most important difference is this binding. Arrow functions use lexical this from the enclosing scope, not dynamic this based on how they're called. This makes them unsuitable for object methods but perfect for callbacks and array methods.
Arrow functions (=>) ES6 में introduce किए गए एक concise syntax हैं। Regular functions से अलग this binding, arguments object, और use में हैं।
| Feature | Regular Function | Arrow Function |
|---|---|---|
| Syntax | function name() { } | (params) => { } |
| this binding | Dynamic - कैसे call हो | Lexical - parent scope से |
| arguments object | हाँ | नहीं, rest parameters use करें |
| Constructor बन सकते हैं | हाँ, new से | नहीं |
| Implicit return | नहीं | हाँ, single expression के लिए |
// Regular function
const add1 = function(a, b) {
return a + b;
};
// Arrow - explicit return
const add2 = (a, b) => {
return a + b;
};
// Arrow - implicit return
const add3 = (a, b) => a + b;
// Single parameter
const double = x => x * 2;
// this binding
const obj = {
name: 'John',
regular: function() {
console.log(this.name); // 'John'
},
arrow: () => {
console.log(this); // Window/global!
}
};इंटरव्यू टिप: सबसे ज़रूरी अंतर this binding है। Arrow functions enclosing scope से lexical this लेते हैं, dynamic this नहीं। यह उन्हें object methods के लिए unsuitable बनाता है पर callbacks के लिए perfect।
Was this answer clear?