How does the this keyword work in JavaScript?
Understand how the this keyword behaves in different contexts — global, function, arrow, and class scopes.
Advertisement
Question
How does the this keyword work in JavaScript?
Answer
this refers to the execution context — the object that owns the current function call.
Its value depends on how the function is called, not where it’s defined.
console.log(this); // Window (in browser)
function show() {
console.log(this);
}
show(); // Window or undefined (strict mode)
const obj = { show };
obj.show(); // obj
const arrow = () => console.log(this);
arrow(); // inherits from lexical scope
Real-World Example
In React class components, this is used to access state and methods — but in functional components, we use hooks to avoid it.
Quick Practice
What will this point to in each case?
function say() {
console.log(this);
}
say();
new say();
Summary
this depends on how a function is called — context is everything.
Does "this" refer to the function itself?
No. It refers to the object that invoked the function, or is bound at call-time depending on context.
Advertisement
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.
Advertisement