Question
How does the JavaScript this keyword work, and when should it be used?
I am looking for a clear explanation of what this does and how to use it correctly. It sometimes appears to behave unexpectedly, and I do not understand why. How is the value of this determined, and when is it appropriate to use it?
Short Answer
By the end of this page, you will know that JavaScript this is usually determined by how a function is called, not where the function was written. You will be able to use this in object methods and classes, avoid common callback problems, and choose between regular functions and arrow functions.
Concept
this is a special JavaScript value available inside many functions. It usually refers to the object associated with the current function call.
The most important rule is:
For a regular function,
thisis determined by the call site: the code that calls the function.
For example, when user.greet() is called, this inside greet is user:
const user = {
name: "Ava",
greet() {
return `Hello, ${this.name}!`;
}
};
console.log(user.greet()); // Hello, Ava!
Here, this.name means user.name because user is the object before the dot in user.greet().
this is useful when code needs to work with the particular object that received a method call. Instead of writing separate functions for every user, product, or account, one method can refer to the current instance through this.
Mental Model
Think of a regular function as an employee who looks at who handed it the current task.
- In
car.start(), the employee sees thatcarhanded over the task, sothismeanscar. - In
bike.start(), the same function can see thatbikehanded over the task, sothismeansbike. - If the function is called by itself, such as
start(), nobody is identified as the caller. In strict mode,thisisundefined.
An arrow function is different: it is like an employee who always follows the instructions of the office where they were hired. It keeps the surrounding this rather than receiving a new one from its caller.
Syntax and Examples
A method can use this to access properties on the object that called it:
const counter = {
count: 0,
increment() {
this.count += 1;
return this.count;
}
};
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
this.count refers to counter.count because increment was called as counter.increment().
The same reusable function can behave differently for different objects:
function describe() {
return `${this.brand} ${this.model}`;
}
phone = { : , : , describe };
laptop = { : , : , describe };
.(phone.());
.(laptop.());
Step by Step Execution
Consider this example:
const playlist = {
name: "Morning Focus",
songs: 12,
addSong() {
this.songs += 1;
console.log(`${this.name}: ${this.songs} songs`);
}
};
playlist.addSong();
Execution trace:
- JavaScript creates the
playlistobject withname,songs, andaddSong. playlist.addSong()calls theaddSongmethod throughplaylist.- Because
playlistis before the dot,thisinsideaddSongisplaylist. - reads , which is initially .
Real World Use Cases
this commonly appears in these situations:
- Class instances: A
ShoppingCartinstance usesthis.itemsandthis.totalto manage its own state. - Object methods: A configuration object uses
thisto read related settings. - UI event handlers: In a regular browser event listener,
thiscan refer to the element receiving the event.event.currentTargetis often clearer and more reliable. - Reusable methods: One function can operate on multiple compatible objects when called as their method.
- Framework and library code: Some older APIs and class-based code use
thisto refer to a component or instance.
Example: a simple cart class:
class ShoppingCart {
constructor() {
this.items = [];
}
addItem(item) {
this.items.push(item);
}
itemCount() {
return ..;
}
}
Real Codebase Usage
In production code, developers use this mostly in methods and classes, while avoiding unclear or accidental bindings.
Use methods for object-owned behavior
const session = {
userId: null,
isAuthenticated() {
return this.userId !== null;
}
};
Use guard clauses with instance state
class FileUploader {
constructor(file) {
this.file = file;
}
upload() {
if (!this.file) {
throw new Error("A file is required.");
}
return `Uploading ${this.file.name}`;
}
}
Preserve this in callbacks when necessary
A common pattern is an arrow callback inside a class method. The arrow captures the method's :
Common Mistakes
Losing this by separating a method from its object
"use strict";
const user = {
name: "Ava",
greet() {
console.log(this.name);
}
};
const greet = user.greet;
greet(); // TypeError: Cannot read properties of undefined
greet() is a plain function call, so it has no object receiver. Call user.greet() instead, or bind the method:
const greet = user.greet.bind(user);
greet(); // Ava
Using an arrow function as an object method when dynamic this is needed
const user = {
name: "Ava",
greet: () => console.log(.)
};
user.();
Comparisons
| Situation | What this is | Example |
|---|---|---|
| Object method call | The object before . | user.greet() → this is user |
| Class instance method | The instance before . | account.deposit() → this is account |
Constructor call with new | The newly created instance | new User("Ava") |
| Plain regular function in strict mode | undefined |
Cheat Sheet
thisis a special value available in regular functions and methods.- For regular functions, inspect how the function is called.
object.method()meansthisis usuallyobject.new Constructor()meansthisis the new instance.functionName()in strict mode meansthisisundefined.- Arrow functions do not get their own
this; they capture the surrounding one. - Use method shorthand when an object method needs
this:
const object = {
value: 1,
getValue() {
return this.value;
}
};
- Use arrow callbacks to retain a surrounding method's
this:
setTimeout(() => .(), );
FAQ
Is this the same as the current object in JavaScript?
Often, but not always. In object.method(), it is usually the object. In a plain function call, it is undefined in strict mode. Arrow functions inherit it from their surrounding scope.
Why is this undefined in my JavaScript function?
The function was likely called without an object receiver, such as fn() rather than object.fn(), and strict mode is active.
Should I use an arrow function for an object method?
Usually no if the method needs this to refer to the object. Use method syntax or a regular function. Arrow functions are useful for callbacks that should retain the surrounding this.
How do I keep this in a callback?
Use an arrow callback, such as setTimeout(() => this.run(), 0), or bind a regular method with this.run = this.run.bind(this).
What does this mean in a class constructor?
It refers to the new instance being created. Assignments like this.name = name store data on that instance.
Mini Project
Description
Build a small TaskList class that keeps a list of tasks. The project demonstrates how this lets each class instance manage its own data through instance methods.
Goal
Create two independent task lists and use this to add tasks, complete tasks, and display each list's summary.
Requirements
- Create a
TaskListclass with a name and an empty task list. - Add an
addTaskmethod that stores a task with adonestatus. - Add a
completeTaskmethod that marks a task as complete by its index. - Add a
summarymethod that returns the list name and completion count. - Create two separate
TaskListinstances to confirm that their data remains independent.
Keep learning
Related questions
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.