Q280 — Behavior of this in Normal Functions vs Arrow Functions
✅ 1. Normal Functions
In normal functions, this is dynamic.
Its value depends on how the function is called, not where it is written.
Example:
const user = {
name: "Teekam",
greet() {
console.log(this.name);
}
};
user.greet(); // Teekam
Called standalone:
const greet = user.greet;
greet(); // undefined (or window.name in non-strict mode)
✔ this changes based on caller
✔ Common source of bugs
✅ 2. Arrow Functions
Arrow functions do not have their own this.
They lexically inherit this from the surrounding scope.
Example:
const user = {
name: "Teekam",
greet: () => {
console.log(this.name);
}
};
user.greet(); // undefined
Why?
- Arrow function takes
thisfrom where it was created (global scope)
🔥 Key Difference Example (Inside Callback)
Normal function (problematic)
function Timer() {
this.count = 0;
setInterval(function () {
this.count++; // ❌ 'this' is window
}, 1000);
}
Arrow function (solution)
function Timer() {
this.count = 0;
setInterval(() => {
this.count++; // ✔ inherits 'this' from Timer
}, 1000);
}
🧠 Summary Table
| Feature | Normal Function | Arrow Function |
|---|---|---|
this |
Dynamic | Lexical |
| Depends on call | ✔ Yes | ❌ No |
Own this |
✔ Yes | ❌ No |
| Good for | Methods, constructors | Callbacks |
🎯 Short Interview Answer
In normal functions,
thisis dynamic and determined by how the function is called.
In arrow functions,thisis lexically bound and inherited from the surrounding scope, making it predictable and ideal for callbacks.
⭐ Best Practice
✔ Use normal functions for object methods and constructors
✔ Use arrow functions for callbacks and nested functions