Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is "this" in JavaScript?

JavaScript is a programming language that allows you to create interactive web applications. You've probably heard of it, and you may have even used it yourself. One of the unique and sometimes confusing aspects of JavaScript is the way it deals with something called this. In this blog post, we'll explore what this is, why it's important, and how you can use it effectively in your code.

What is this?

In JavaScript, this is a special keyword that refers to the current context in which a function is being executed. It's a way for a function to access the object that it belongs to or the object that called it. To put it in simpler terms, this is like a pronoun in a sentence, a way for a function to refer to itself or its "owner" without having to use the actual name of the object.

Let's look at a real-life analogy to help you understand the concept of this. Imagine that you're at a party, and someone says, "Hey, can you pass me the chips?" In this context, "me" refers to the person who is asking for the chips. They don't have to say their name; they just say "me" to stand in for their identity. In JavaScript, this serves a similar purpose, allowing a function to refer to the object that it is associated with.

An example of this in action

Let's dive into some code examples to further illustrate the concept of this. Consider the following object, which represents a simple counter:

const counter = {
  count: 0,

  increment: function() {
    this.count++;
  }
};

Here we have an object called counter with a property called count, which is initially set to 0. We also have a method called increment, which increases the value of count by 1. Notice how we use this.count to refer to the count property of the counter object. When we call counter.increment(), the value of this inside the increment function will be the counter object, so this.count refers to counter.count.

console.log(counter.count); // Output: 0
counter.increment();
console.log(counter.count); // Output: 1

How this gets its value

Now that we've seen this in action, you might be wondering how JavaScript determines the value of this in a given context. The answer is that it depends on how a function is called. There are four main ways a function can be called in JavaScript, and each one affects the value of this differently:

  1. As a method on an object
  2. As a standalone function
  3. As a constructor
  4. Using call(), apply(), or bind()

Let's take a closer look at each of these cases.

1. As a method on an object

When a function is called as a method on an object, like in our counter example above, the value of this is set to the object that the method is being called on.

const myObject = {
  name: 'Alice',
  greet: function() {
    console.log('Hello, ' + this.name + '!');
  }
};

myObject.greet(); // Output: "Hello, Alice!"

2. As a standalone function

When a function is called on its own, not as a method on an object, the value of this is set to the global object (window in a browser environment, or global in a Node.js environment). This is often not what you want, and it can lead to bugs if you're not careful.

function greet() {
  console.log('Hello, ' + this.name + '!');
}

const name = 'Alice';
greet(); // Output: "Hello, Alice!" (because `this` is the global object)

To avoid this issue, you can use "strict mode" by adding the line 'use strict'; at the beginning of your script or function. In strict mode, the value of this in a standalone function will be undefined, which can help you catch errors more easily.

'use strict';

function greet() {
  console.log('Hello, ' + this.name + '!');
}

greet(); // Output: "Hello, undefined!"

3. As a constructor

When a function is called with the new keyword, it acts as a constructor, creating a new object and setting the value of this to that new object. This is a common pattern in object-oriented programming.

function Person(name) {
  this.name = name;
  this.greet = function() {
    console.log('Hello, ' + this.name + '!');
  };
}

const alice = new Person('Alice');
alice.greet(); // Output: "Hello, Alice!"

4. Using call(), apply(), or bind()

JavaScript provides three special methods that allow you to explicitly set the value of this when calling a function: call(), apply(), and bind(). These methods can be very useful for controlling the context in which a function is executed.

function greet() {
  console.log('Hello, ' + this.name + '!');
}

const alice = {name: 'Alice'};
const bob = {name: 'Bob'};

greet.call(alice); // Output: "Hello, Alice!"
greet.apply(bob); // Output: "Hello, Bob!"

const greetAlice = greet.bind(alice);
greetAlice(); // Output: "Hello, Alice!"

Conclusion

Understanding this in JavaScript is an essential part of mastering the language. It can be a bit tricky at first, but with practice and a solid grasp of the different ways that this can be set, you'll be able to write more flexible and powerful code. Just remember to pay attention to how your functions are being called, and don't be afraid to use tools like "strict mode" and the call(), apply(), and bind() methods to help you control the value of this in your code.