Function Returning This

Function Returning This

When we define a function in JavaScript, it always returns something. By default, if we don't explicitly return a value from a function, it returns undefined. However, we can use the return keyword to return a value from a function.

When we use the this keyword inside a function, it refers to the object that the function is a method of. In other words, it refers to the object on which the function is called.

Let's take an example to understand this concept better.


let person = {
  name: 'John',
  age: 30,
  getInfo: function() {
    return 'Name: ' + this.name + ', Age: ' + this.age;
  }
};

console.log(person.getInfo()); // Output: Name: John, Age: 30

In the above example, we have defined an object named person with two properties name and age, and a method named getInfo. The getInfo method returns a string that contains the name and age of the person object. Inside the method, we have used the this keyword to refer to the person object.

We can also use the return keyword to return the object itself from the function. This can be useful when we want to chain multiple methods together.


let person = {
  name: 'John',
  age: 30,
  getInfo: function() {
    return this;
  },
  incrementAge: function() {
    this.age++;
    return this;
  }
};

console.log(person.getInfo().incrementAge().getInfo()); 
// Output: { name: 'John', age: 31, getInfo: [Function], incrementAge: [Function] }

In the above example, we have added a new method named incrementAge to the person object. The incrementAge method increments the age of the person object and returns the object itself. We can chain multiple methods together by returning the object from each method.

In conclusion, the this keyword inside a function refers to the object on which the function is called. We can use the return keyword to return a value from a function or to return the object itself.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe