programming
javascript
coding tutorials
this keyword
software development

How does the this keyword work, and when should it be used?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In many programming languages, the this keyword is fundamentally important and widely used. It provides a reference to the object that is currently invoking a method or constructor. Understanding how this works and when to use it is crucial for writing efficient and error-free object-oriented code.

Understanding the "this" Keyword

In JavaScript

JavaScript's this keyword behaves a bit differently depending on the context in which it's used:

  1. Global Context:
    • In the global execution context (outside of any function), this refers to the global object whether in strict mode or not. In a browser, it's window.
javascript
console.log(this === window); // true
  1. Function Context:
    • In a regular function, the value of this depends on how the function is called. If it is not part of an object, this will default to the global object (window in a browser), or be undefined in strict mode.
javascript
1function show() {
2  console.log(this === window);
3}
4show(); // true in non-strict mode, false in strict mode
  • If the function is called as a method of an object, this is bound to the object the method is called on.
javascript
1const obj = {
2  name: "Example",
3  show: function () {
4    console.log(this.name);
5  },
6};
7obj.show(); // "Example"
  1. Arrow Functions:
    • Arrow functions do not have their own this. Instead, this is inherited from the parent scope at the time the arrow function is defined.
javascript
1const obj = {
2  name: "Example",
3  show: () => console.log(this.name),
4};
5obj.show(); // undefined or depends on where obj is defined
  1. With new Keyword:
    • When a function is used as a constructor (with the new keyword), this is bound to the new object being created.
javascript
1function Person(name) {
2  this.name = name;
3}
4const p = new Person("John");
5console.log(p.name); // "John"

In Java

In Java, this is simpler. It always refers to the current instance of the class in which it's used.

  1. Referring to instance variables:
    • It's common to use this to differentiate between instance variables and parameters when they have the same name.
java
1   public class Car {
2     private String color;
3
4     public Car(String color) {
5       this.color = color;
6     }
7   }
  1. Chaining Constructors:
    • Within a constructor, this() can be used to invoke another constructor in the same class.
java
1   public class Rectangle {
2     private int x, y;
3     private int width, height;
4
5     public Rectangle() {
6       this(0, 0, 1, 1);
7     }
8
9     public Rectangle(int width, int height) {
10       this(0, 0, width, height);
11     }
12
13     public Rectangle(int x, int y, int width, int height) {
14       this.x = x;
15       this.y = y;
16       this.width = width;
17       this.height = height;
18     }
19   }

Summary Table

ContextBehavior in JavaScriptBehavior in Java
GlobalRefers to global object (window in browser)Not applicable
FunctionVaries: global object or undefined in strict mode, object if called as a methodRefers to current instance
Arrow FunctionInherits from parent scopeNot applicable
ConstructorBinds to the new object being createdRefers to the current instance being created

When to Use this

  • JavaScript:
    • To access or modify properties of the object.
    • In constructors to initialize new objects.
    • To maintain context in event handlers and callbacks (prefer arrow functions for automatic context binding).
  • Java:
    • To distinguish between fields and parameters with the same name.
    • To invoke one constructor from another in the same class.

Understanding and using this appropriately can help avoid common pitfalls such as unintended referencing of the global object or wrong contexts in callbacks, leading to more robust and maintainable code. Always consider the scope and binding rules of this in the specific language and context you are working in.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions