Arrow functions and this in JavaScript

🔍 "this" behaves differently in arrow functions. ❓ Why does this not bind in arrow functions—and when is that useful? In JavaScript, the value of this usually depends on how a function is called. But arrow functions work differently. 👉 Arrow functions do NOT have their own this. Instead, they inherit this from their surrounding (lexical) scope. 🔹 Simple example const user = { name: "Isnaan", greet: function () { setTimeout(() => { console.log(this.name); }, 1000); } }; user.greet(); // "Isnaan" Here’s why this works: greet() is a normal function, so this refers to user. The arrow function inside setTimeout inherits this from greet, instead of creating its own. ❌ What happens without arrow functions? setTimeout(function () { console.log(this.name); }, 1000); // undefined ❌ Because this now points to the global object. ✅ When is this useful? Inside callbacks (setTimeout, event handlers, promises) In React components and hooks When you want predictable this without .bind() 💡 Takeaway: Arrow functions keep this simple and predictable—but avoid them as object methods when you need dynamic this #learnwithisnaan #mernstackdeveloper #JavaScriptTips #ModernJavaScript #ES6 #DeveloperTips #CleanCode #JSDevelopers

  • text

To view or add a comment, sign in

Explore content categories