The value of this in JavaScript depends on how a function is called — not where it’s defined. It can refer to the global object, a specific object, or be undefined in strict mode or arrow functions. The value of this depends on call site, strict mode, and arrow functions. Misbinding is a common source of bugs; test with call/apply/bind.
Explain the `this` keyword in JavaScript
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
The Core Idea
The value of this in JavaScript is determined by how a function is called, not by where it is written. It points to the execution context — the object that 'owns' the function at the time of invocation.
Call Type | Value of | Example |
|---|---|---|
Global / Default | In browsers → |
|
Object method | The object before the dot |
|
Constructor | The newly created instance |
|
Explicit binding | Set manually using |
|
Arrow function | Does not bind |
|
// Example 1: Default binding
function show() {
console.log(this);
}
show(); // window (or undefined in strict mode)
// Example 2: Method call
const user = {
name: 'Mia',
greet() {
console.log('Hi, ' + this.name);
}
};
user.greet(); // 'Hi, Mia'
// Example 3: Detached method loses context
const greetFn = user.greet;
greetFn(); // undefined or 'Hi, undefined' — this is lost
Fixing Lost Context
You can control or preserve this explicitly using:
call()/apply()→ call immediatelybind()→ return a new function with fixedthis
const boundGreet = user.greet.bind(user);
boundGreet(); // 'Hi, Mia'
Arrow Functions
Arrow functions don’t have their own this. They inherit it from the surrounding scope. Great for callbacks that need lexical this.
function Timer() {
this.seconds = 0;
setInterval(() => {
this.seconds++;
console.log(this.seconds);
}, 1000);
}
new Timer(); // works fine
// But using a normal function would break:
// setInterval(function() { this.seconds++ }, 1000); // this = undefined
Common Pitfalls
- Forgetting
new→thisbecomes global (or undefined in strict mode) - Losing context when passing methods as callbacks
- Misusing arrow functions in class methods (they can’t be rebound)
Practical scenario
A class method passed as a callback loses this, breaking access to instance state.
Common pitfalls
- Forgetting to bind methods in constructors.
- Using arrow functions and expecting dynamic this.
- Calling functions without a receiver in strict mode.
Binding is explicit but creates new functions. Test with call/apply/bind and verify this values.
Think of this as the person holding the phone 📱 — not the number you dialed. The number (function) stays the same, but who picks up (the object that calls it) decides what this will be.
thisdepends on the call site, not where the function is defined.- Arrow functions don’t have their own
this. call,apply, andbindlet you controlthisexplicitly.newcreates a new object and bindsthisto it.