Arrow functions छोटे होते हैं, लेकिन असली अंतर सिर्फ़ syntax में नहीं बल्कि binding behavior में है।
const regular = function () {};
const arrow = () => {};
const short = x => x * 2; // implicit return for one expression
Arrow functions छोटे होते हैं, लेकिन असली अंतर सिर्फ़ syntax में नहीं बल्कि binding behavior में है।
const regular = function () {};
const arrow = () => {};
const short = x => x * 2; // implicit return for one expression
1. अपना कोई this नहीं — arrows this को enclosing scope से inherit करते हैं। यह सबसे महत्वपूर्ण अंतर है और इसीलिए वे callbacks के लिए बेहतरीन हैं:
const timer = {
seconds: 0,
start() {
setInterval(() => this.seconds++, 1000); // ✅ `this` is timer
// a regular function here would have its own `this` (undefined) → bug
},
};
2. कोई arguments object नहीं — इसके बजाय rest parameters का उपयोग करें:
const sum = (...args) => args.reduce((a, b) => a + b, 0);
3. Constructors के रूप में उपयोग नहीं किए जा सकते — new arrow() throw करता है, और उनके पास कोई prototype नहीं होता।
const obj = {
name: "Ann",
greet: () => `Hi ${this.name}`, // ❌ `this` is NOT obj (it's outer scope)
greet2() { return `Hi ${this.name}`; }, // ✅ method needs dynamic `this`
};
Object methods के लिए arrows का उपयोग न करें (वे object से bind नहीं होंगे) या जब आपको dynamic this/arguments की ज़रूरत हो (ऐसे event handlers जो this के element होने पर निर्भर करते हैं)।
Callbacks और छोटे functions के लिए arrows का उपयोग करें जहाँ this को inherit करना आपकी इच्छा हो; methods, constructors और prototype methods के लिए regular functions का उपयोग करें।
विस्तृत उत्तरों के साथ IT इंटरव्यू प्रश्नों की एक लाइब्रेरी — जूनियर से सीनियर तक।
दान करें