Skip to content
the poor coder

Function Returning This

Poor Man
Published
Reading time
2 min read

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.

Text

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.

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC