Understanding the this Keyword in JavaScript

Day 22/50 – JavaScript Interview Question? Question: What is the this keyword and how is it determined? Simple Answer: this refers to the object that is executing the current function. Its value is determined by how the function is called: in a method it's the object, in a regular function it's the global object (or undefined in strict mode), in an arrow function it's lexically inherited from the enclosing scope. 🧠 Why it matters in real projects: Understanding this is critical for object-oriented programming, event handlers, and React class components. Incorrect this binding is one of the most common sources of bugs, especially when passing methods as callbacks. 💡 One common mistake: Losing the this context when passing object methods as callbacks (like event handlers), resulting in this being undefined or pointing to the wrong object. 📌 Bonus: const user = { name: 'Alice', greet: function() { console.log(`Hello, ${this.name}`); }, greetArrow: () => { console.log(`Hello, ${this.name}`); // Won't work! } }; user.greet(); // "Hello, Alice" ✓ const greetFunc = user.greet; greetFunc(); // "Hello, undefined" - lost context! // Solutions for callback context: // 1. Bind button.addEventListener('click', user.greet.bind(user)); // 2. Arrow function wrapper button.addEventListener('click', () => user.greet()); // 3. Arrow function in class (React) class Component { handleClick = () => { // Auto-bound! console.log(this); } } #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #ThisKeyword #InterviewPrep #OOP

Nicely explained. this is determined by the call site, not the definition losing context in callbacks is where most bugs sneak in

Like
Reply

To view or add a comment, sign in

Explore content categories