🧭 Arrow Functions vs Function Declarations in JavaScript
Category: js / general-concepts
Difficulty: easy
Why this.fire = function(...) and not an arrow function? Here's the full breakdown. 1️⃣ Introduction JavaScript offers multiple ways to define functions: Function Declarations: function greet() {} Function Expressions: const greet = function() {} Arrow Functions: const greet = () => {} While arrow functions offer brevity and clarity, they do not have their own this , which is why choosing between the two depends entirely on your use case. 2️⃣ The Key Difference: this Binding Function Expressions Function expressions define their own this context depending on how they're called: [code example] Arrow Functions Arrow functions lexically bind this , meaning they inherit this from the surrounding context: [code example] 📌 Why Not Use Arrow in this.fire = function (...)? Because this refers to the object instance (Move in this case), and the fire method needs to explicitly bind thisObj or use the current instance as context. If you used an arrow function, it would ignore thisObj and this would not refer to the Move instance or a provided scope — breaking functionality like .call(): [code example] 3️⃣ When to Use Which Prefer Function ✅ Yes ✅ Yes ✅ Yes ✅ Usually ❌ Overhead 4️⃣ Real Examples ✅ Good Use of Arrow: [code example] ✅ Good Use of Function Declaration: [code example] ⚠️ Misuse of Arrow in Object Method: [code example] 5️⃣ Interview Q&A Q1: Why don’t arrow functions have their own this? A: Because arrow functions are designed for lexical scoping. They inherit this from the context in which they are defined, rather than from how they are called. Q2: When would using an arrow function inside a class break things? A: When the method depends on this referring to the class instance. Arrow functions don’t have their own this, so they won’t work properly in instance methods. Q3: Can you replace all function expressions with arrow functions? A: No. If the function needs a dynamic or context-based this, you must use a traditional function. Q4: How does .call() or .apply() ...