Using fat arrow functions in your Node module

Functions are first-class citizens in JavaScript. This is one of the most popular aspects of the language. It is also one of the most powerful features. When a function is a property of an object, it is also considered a method of that object. Inside of a method, the this keyword provides value. It allows us to access the object to which the method belongs, and its other properties.

There is a tricky aspect to the this keyword when nesting functions. It is one of the more frustrating aspects of the language. I this article, I will discuss this problem and how to solve it using fat arrow functions.

To get started, clone the following git hub repository:

https://github.com/kevinchisholm/using-fat-arrow-functions-in-your-node-module

(Instructions on how to run the code are available in the Git hub page.)

An important note about the code examples:

The titles of this article references "...your node module". I wanted to keep things simple, so I did not use a node module for the context of the code examples. In the real world, most Node applications keep the main file code minimal. Taking a modular approach is almost always recomended. For this article, I have put the code in the main JavaScript file.

The problem with "this"

Example # 1:

//create a tools object
var tools = {
    message: 'Hello from this.message!',
    asyncTask: function () {
 
        //simulate an asynchronous task
        setTimeout( function () {
            console.log('THE MESSAGE IS: ' + this.message);
        }, 1000);
    }
};
 
//call asyncTask
tools.asyncTask();

Run example # 1 in your terminal with the following command: node example-1.js.

The result of this is: "THE MESSAGE IS: undefined".

In example # 1, we have created a tools object. The name "tools" is arbitrary, it could have been any name. We just want an object to work with.

The "tools" object has a property called "message". There is also a method named "asyncTask". The asyncTask method simulates an asynchronous task by using the setTimeout method. Inside of the anonymous function passed to the setTimeout method, there is a reference to the this keyword. The anonymous function passed to the setTimeout method is not executed in the context of the "tools" object. This is a problem. As a result, the result of the console.log message is: "THE MESSAGE IS: undefined".

We need a way to reference the "tools" object inside of the anonymous function passed to the setTimeout method. The best approach is still to reference the "this" keyword. A common approach is to set a reference to "this" before calling the setTimout method. This has been a popular technique in the past. While that is still a possible technique, there is a more elegant approach.

How fat arrow functions solve the "this" problem

Example # 2:

//create a tools object
var tools = {
    message: 'Hello from this.message!',
    asyncTask: function () {
 
        //simulate an asynchronous task
        setTimeout( () => {
            console.log('THE MESSAGE IS: ' + this.message);
        }, 1000);
    }
};
 
//call asyncTask
tools.asyncTask();

Run example # 2 in your terminal with the following command: node example-2.js.

The result of this is: "THE MESSAGE IS: Hello from this.message!"

In example # 2, we made a small change. We converted the anonymous function passed to the setTimeout method to a fat arrow function. This action solved our problem. One of the big advantages to fat arrow functions is that they preserve the meaning of the this keyword. As a result, when re reference this.message we no longer have an error. Also, we see the expected message in the console.

Fat arrow function arguments

Example # 3A:

someFunction( message => {
    console.log('THE MESSAGE IS: ' + message);
});

Example # 3B:

someFunction( (message1, message2) => {
    console.log('THE MESSAGE IS: ' + message1 + ' and ' + message2);
});

You may have noticed that in example # 2, the fat arrow function takes no argument. But, it still has a pair or opening and closing parentheses. When a fat arrow function takes no arguments, then you must include a pair or opening and closing parentheses.

In example # 3A, notice that there are no parentheses in the fat arrow function. When there is one argument, then you do not need to include parentheses. In example # 3B, notice that there are two arguments contained inside of parentheses. When there is more than one argument, then you must include parentheses.

Summary

In this article, we learned how fat arrow functions solve the "this" problem. They provide a access to the object to which the containing function belongs. You can access that object at all times by using the "this" keyword. We also learned that when defining the function, the parentheses are not needed in some cases.

Author

Kevin Chisholm

http://blog.kevinchisholm.com

Share This