Why Use "this" Instead of the Object Name to Reference the Object's Properties in JavaScript?

When we're working with objects in JavaScript, using this inside an object allows us to reference its properties.

But why is it preferred over simply using the object's name to reference the same property?

For example, why is it better to write:

const person = {
  name: "John Doe",
  greet: function () {
    console.log(`Hello, my name is ${this.name}`);
  },
};

Verses

const person = {
  name: "John Doe",
  greet: function () {
    console.log(`Hello, my name is ${person.name}`);
  },
};

Here are a few reasons as why using this is preferred:

1. Flexibility with Instances

When you're dealing with one-off objects like in the above example, it might seem unnecessary to use this. However, when you're working with classes or constructors to create multiple instances of objects, the importance of this becomes apparent.

Take this class-based example.

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  sayHello() {
    console.log(`Hello, my name is ${this.name}!`);
  }
}

const stevePerson = new Person("Steve", 33);
const gregPerson = new Person("Greg", 33);

stevePerson.sayHello(); // Logs "Hello, my name is Steve"
gregPerson.sayHello(); // Logs "Hello, my name is Greg"

Here, we can create multiple instances of the Person class, each with its unique name property. Inside the sayHello method, we don't need to worry about which instance is calling the function; this dynamically refers to the calling instance.

2. Code Maintainability

Using this promotes code that is easier to maintain and refactor.

If you decide to rename the object in the future, you only need to change it once if you're using this consistently. In contrast, if you're directly referencing the object's name throughout your code, you'll need to update every instance of it.

3. Clarity and Readability

Using this enhances the readability of your code. It makes it clear that you're referring to a property of the current object, improving code comprehension.

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda