JavaScript this keyword behavior with destructuring

🧩 JavaScript Output-Based Question (`this` + destructuring) ❓ What will be logged? 👉 Comment your answer below (Don’t run the code ❌) Correct Output : undefined 🧠 Why this output comes? (Step-by-Step) 1️⃣ Method works only when called on the object user.getName(); // "Jyoti" 2️⃣ Destructuring extracts the function, not the context const { getName } = user; Here, getName becomes a plain function reference. 3️⃣ Function is called without an object getName(); So: • this is lost • this → global object / undefined (strict mode) • this.name → undefined That’s why nothing is printed. 🔑 Key Takeaways ✔️ this depends on how a function is called ✔️ Destructuring methods breaks their context ✔️ Methods should be bound before destructuring if this is used Extracting a method ≠ calling it as a method #JavaScript #ThisKeyword #InterviewQuestions #FrontendDeveloper #MERNStack #WebDevelopment

  • text

Undefined, Solun: 1) user.getName() 2) get Name.call(user)

Undefined. Regular Functions rely on how they are called. Since its called by the window object, where name is undefined, its returns the same. Can be fixed by using call, bind

Nice post! You can bind the correct "this" to a destructured function using "Function.prototype.call", which explicitly sets the context. getName.call(obj) // "Jyoti"

See more comments

To view or add a comment, sign in

Explore content categories