'this' in JavaScript: A Beginner's Guide

'this' in JavaScript: A Beginner's Guide

·

2 min read

When I first started learning JavaScript, one of the concepts that I found a bit tricky to understand was the this keyword. I'll try to make it simpler for you with this article, by breaking down exactly what this is, when, and how to use it, and some tips to keep in mind as you're working with it.

First things first, let's define what this is. In JavaScript, this refers to the object that the function is a property of. In other words, it's a way to access the object that the function is a part of. Think of this as a magical word that gives you access to the object you are currently working with.

So, when should you use this? One of the main reasons to use this is to access properties and methods of an object within the object's own methods. For example, let's say you have an object called "person" that has properties like "name" and "age" and a method called "greet()". Within the "greet()" method, you can use this to access the person's name and age and use them in the greeting.

let person = {
  name: "John Doe",
  age: 30,
  greet: function() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`)
  }
}
person.greet(); // "Hello, my name is John Doe and I am 30 years old."

Another common use case for this is in event handlers. When an event occurs on a web page, the event is passed to an event handler function. Within that function, this refers to the element that the event occurred on.

let button = document.querySelector("button");
button.addEventListener("click", function() {
  console.log(`The button with text "${this.innerHTML}" was clicked!`);
});

Even though this can be a bit overwhelming at first, here are a few tips to keep in mind as you're working with this:

  1. Always pay attention to the context in which this is being used. Is it within an object's method? Is it within an event handler? The context will determine what this is referring to.

  2. Be careful when using this within nested functions or arrow functions. The value of this can be different within those nested or arrow functions than it is in the parent function.

  3. To set the value of 'this' in nested functions or arrow functions we can use bind, call, apply method.

  4. If you're ever not sure what the value of this is, you can use the console.log(this) to print the value of this in the current context

I hope that this breakdown of the this keyword in JavaScript has been helpful for you as a new developer. Happy coding!