🧩 JavaScript Output-Based Question (`this` + setTimeout) ❓ What will be the output? 👉 Comment your answer below (Don’t run the code ❌) Output : undefined 🧠 Why this output comes? (Step-by-Step) 1️⃣ print() is called as a method obj.print(); So inside print, this correctly refers to obj. 2️⃣ But inside setTimeout… setTimeout(function () { console.log(this.name); }, 0); The callback is a regular function, not a method of obj. When it executes: • this does NOT refer to obj • In non-strict mode → this points to the global object • In strict mode → this is undefined Either way: this.name → undefined 3️⃣ The key mistake Assuming this is preserved automatically in async callbacks ❌ 🔑 Key Takeaways ✔️ this depends on how a function is called ✔️ setTimeout callbacks lose object context ✔️ Use arrow functions or bind to fix this ✔️ This bug appears frequently in real projects Async code doesn’t preserve this by default. How would you fix this so it prints "JS"? 👇 Drop your solution in comments #JavaScript #ThisKeyword #InterviewQuestions #FrontendDeveloper #MERNStack #WebDevelopment
to get respective answer, just bind the function with the obj and call it.
Undefined as this is call in the window api which is set time out
Use an arrow function in setTimeout so it keeps the lexical this: setTimeout(() => console.log(this.name), 0);
Undefined
Undefined Because naming functions take context when you call them as you are calling the function in global scope means that time context should be the windows obj and there will no name variable inside windows object so that is why ‘Undefined’ comes as an output
Solution is to convert the function in setTimeout() to arrow function as it refers to it's parent/surrounding for "this".