Fat Arrow Function Basics – Node Modules

Node.js

JavaScript LogoJavaScript Fat Arrow Functions solve the “this” problem by maintaining a reference to the object to which a method belongs. This is the case even with nested functions.

One of the most popular aspects of JavaScript is the fact that functions are first-class citizens. So, this aspect of the ECMAScript specification provides a great deal of power. Now when a function is a property of an object, it is also considered a method. That is, it is a method of that object. And inside of a method, the JavaScript “this” keyword is important, because it allows us to access the object to which the method belongs, as well as its other properties.

Now, when nesting functions, the JavaScript “this” keyword, one of the more frustrating aspects of the language, can be a bit tricky to deal with. So, in this article, I will discuss this very problem and how to solve it using fat arrow functions. If you’d like to run the code examples locally on your computer, clone the following github repository: Using fat arrow functions in your Node module.

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

One important note about the code examples: the title of this article references “…Node Modules” to keep things simple, so I did not use a node module for the context of the code examples. Most Node applications keep the main file code minimal. Taking a modular approach is almost always a best practice, but for this article, I have put the code in the main JavaScript file.

The problem with “this” – Example # 1

Run Example # 1 in your terminal with the following command: node example-1.js. The result of this is: “THE MESSAGE IS: undefined“.

We have created a tools object in Example # 1, and that name is “tools“, which is arbitrary. It could have been any name, we just need an object to work with. The “tools” object has a “message” property, and there is also a method named “asyncTask“. The asyncTask method simulates an asynchronous task by using the setTimeout method. There is a reference to the JavaScript “this” keyword inside of the anonymous function passed to the setTimeout method. Now here’s where it gets a little dicey: the anonymous function passed to the setTimeout method is not executed in the context of the “tools” object, and therein lies the problem. The resulting console.log message is: “THE MESSAGE IS: undefined“.

So, we need a way to reference the “tools” object inside of the anonymous function that we passed to the setTimeout method. Well, the best approach is still to reference the “this” keyword. A common and popular approach in the past has been to set a reference to “this” before calling the setTimout method. For example: “var me = this;”. Okay, so while that is still a possible technique, there now is a far more elegant approach.

Fat arrow functions solve the “this” problem – Example # 2

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!”

We made a small change in Example # 2. We converted the anonymous function passed to the setTimeout method to a fat arrow function. Fortunately, this action solved our problem. One of the advantages of fat arrow functions is that they preserve the meaning of the JavaScript “this” keyword. Because of this, when we reference this.message we no longer have an error, and we also see the expected message in the console.

Fat Arrow Function – One Argument – Example # 3A

Fat Arrow Function – Multiple Arguments – Example # 3B

A few things to keep in mind:

  • In Example # 2, the fat arrow function takes no arguments, but, it still has a pair of opening and closing parentheses. This is because when a fat arrow function takes no arguments, you must include a pair of opening and closing parentheses.
  • In Example # 3A, there are no parentheses in the fat arrow function. This is because when there is one argument, you do not need to include parentheses.
  • In Example # 3B, there are two arguments contained inside of parentheses. This is because when there is more than one argument, you must include parentheses.

Summary

In this article we saw that fat arrow functions solve the “this” problem because they provide access to the object to which the containing function belongs, and you can access that object at all times by using the “this” keyword. And even when nesting fat arrow functions, the “this” reference is preserved, eliminating the need to set a temporary reference to “this”. Just keep in mind the importance of how the syntax can differ, depending on the number of arguments that the fat arrow function takes. In other words, with zero or multiple arguments, parentheses are required, and with only one argument parentheses are not required. Pretty simple, once you get used to it.

Getting Started with ECMAScript 6 Arrow functions – The “this” keyword

JavaScript

ECMAScript 6 LogoOther than syntax, the biggest change that ECMAScript Arrow Functions brings about, is how it relates to context: in the function body, “this” has a different meaning than you may expect.

It seems to me that the two problems that are solved by ECMAScript 6 Arrow functions are: verbose syntax and the tricky nature of “this” inside a function. Granted, when working with methods and constructors, the meaning of “this” is a bit easier to understand. But when working with functions that are not constructors, or not bound to an object, the “this” keyword will resolve to the window object, and that is rarely the behavior you want. In a function that is defined in the global scope, it is probably unlikely that you will intentionally want to refer to “this” (and global function declarations should really be kept to a minimum or even better, avoided at all costs). But when you have a function that is declared inside of a method for example, it is not at all uncommon to attempt access to “this” from the nested function. This is where the frustration starts, because the meaning of “this” will vary depending on the circumstances.

Example # 1A

In Example # 1A, the object foo has two properties: “color”, whose value is: “red”, and the method: “getColor”. The method foo.getColor has a nested function: privateGetColor, which references “this”. The problem is: inside of privateGetColor, “this” refers to the window object. Since there is no window.color, privateGetColor returns: “undefined”, which means that foo.getColor() returns “undefined”.

Example # 1B

In Example # 1B, we have fixed the situation by creating a private variable named: “me” inside of foo.getColor, which caches “this”. This way, the nested function: “privateGetColor” now has access to “this”, and this foo.getColor returns “red”.

Example # 2

In Example # 2, we have a more elegant solution. By leveraging an arrow function, we no longer need to create the variable “me”, in order to cache the value of “this”. Now that the nested function: privateGetColor is an arrow function, we can reference “this” in the arrow function’s body. Since privateGetColor now returns “red”, foo.getColor() returns “red”.

Lexical binding of “this”

The reason that Example # 2 saves the day, is because of the change in meaning for the “this” keyword inside of an arrow function. Normally, “this” will refer to the object of which the function is a method. With arrow functions, “this” is bound lexically. This means that it is where an arrow function is defined that affects the meaning of “this”, not where it is executed.

Example # 3

In Example # 3, we have an object named “bar”, which has a “color” property. When we execute foo.getColor(), we use the call method to change the context in which getColor is executed. This should have changed the meaning of “this” to “bar”, which would result in the return value of “blue (i.e. privateGetColor.call(bar) should return: “blue”). But that is not what happens; the return value of foo.getColor() is: “red”.

The reason for all of this is that inside of an arrow function, “this” is bound lexically. So, it is where an arrow function is DEFINED, not where it is executed, that determines the meaning of “this”. It might help of think of how scope works in JavaScript. The lexical binding of “this” inside the body of an arrow function behaves in a similar way. The closest containing object outside of the arrow function will be resolved as “this”.

Summary

The meaning of “this” inside an arrow function is without doubt a significant change in the JavaScript specification. Since ECMAScript 6 is 100% backwards-compatible, this has no effect on the meaning of “this” inside of normal function definitions, function expressions, constructors or methods. While it may take a while to get used to this concept, the ramifications are very positive. The ability to reference a specific object inside of a click-handler or AJAX calls makes for code that will be easier to read, manage and extend.

Getting Started with ECMAScript 6 Arrow function Parameters

JavaScript

ECMAScript 6 Logo - arrow functions parametersThere is a tremendous amount of flexibility when it comes to parameters in Arrow Functions.

In the previous article: “Getting Started with ECMAScript 6 Arrow functions – Basic Syntax,” we had a very basic overview of ECMAScript 6’s Arrow Functions and their syntax. In this article, I’ll dive a little deeper into the topic of parameter.

In the previous article, we learned how the parameter(s) now come first, and then the “=>” characters, which effectively replace the “function” keyword. This is very efficient and is a key aspect to the simplicity of arrow functions. But it won’t take long before you’ll want to accept multiple parameters in your arrow function. And of course, you may want to accept no parameters.

Example # 1

In Example # 1, the function addTwoNumbers accepts two parameters. This differs from all of the examples in the previous article, each of which dealt with only one parameter. In ECMAScript 6’s arrow function, when you need to accept multiple parameters, you leverage syntax which should be quite familiar to you: enclose the parameters in parentheses.

Arrow Functions that Take No Parameters

In situations in which you’ll want to accept no parameters, the syntax will be empty parentheses.

Example # 2

In Example # 2, we have the function: returnHello. This function takes no parameters and simply returns the string: “hello”. It is certainly not a very useful function, but the main point here is that if you need to create an arrow function that takes no parameters, simply use a set of empty parentheses in place of what would have been a single parameter or parentheses that contained multiple parameters.

The Arguments Object

According to the ECMAScript Language Specification ECMA-262 6th Edition – DRAFT, “Arrow functions never have an arguments objects.” At the time of this writing, version 33.1 of FireFox does allow access to the arguments object inside of an arrow function.

Example # 3

Running Example # 3 in the JavaScript console of FireFox 33.1 demonstrates that the argument object is, in fact, available inside of an arrow function. I’m not sure if this is a mistake or an intentional disregard for the specification. For now, it’s probably best to not attempt access to the arguments object inside of an arrow function.

Summary

In this article we talked about parameters in ECMAScript 6 Arrow Functions. We discussed how to accepts multiple parameters, as well as how to specify none. We also talked a bit about access to the arguments object inside an arrow function. In the next article, I will discuss the value of “this” inside an arrow function.

Getting Started with ECMAScript 6 Arrow functions – Basic Syntax

JavaScript

ECMAScript 6 Logo - arrow function syntaxArrow functions provide a terse syntax, making for code that is more concise and flexible.

One of the most significant features of the ECMAScript 6 specification is arrow functions. Also referred to sometimes as “fat functions,” this change radically alters the rules with regard to functions in JavaScript. Initially, I had planned on writing an “Introduction to / Overview” article about arrow functions. But since code samples are always helpful, I didn’t want an “Overview” article that had code examples for every aspect of arrow functions. Instead, I decided to just jump in, and create an article that focuses on each area of importance. So this article provides a very simple introduction to general arrow function syntax.

Perhaps the hardest part to get used to with regard to ECMAScript 6 arrow function syntax is the fact that the “function” keyword and parameters are reversed. In addition, the “function” keyword is replaced by: “=>”. So, the end result is:

The above example is pseudo code, but my intention was to demonstrate the correct syntax for arrow functions. So let’s look at a working example:

Example # 1A

 Example # 1B

In Example # 1A, we have the standard syntax you would use when creating an anonymous function expression. That is, the function “addOne” takes a single parameter (a number), and returns that number plus one.

Now in Example # 1B, we have accomplished the exact same result, using arrow function syntax. The “var addOne =” portion of the code should be familiar to you. But it’s after the assignment operator, that things start to look quite different. First, we next have the single parameter: “someNumber”. That parameter is followed by: “=>”. This equal+greater than character combination replaces the “function” keyword. Next we have the function body.

The Function Body

In Example # 1B, you may have noticed the absence of the curly braces. This is because the body of our arrow function consisted of one expression. In this case, the curly braces can be omitted. When the arrow function consists of more than one expression, then curly braces are required. Also, when the function body consists of a single expression, the implicit return value of the function is the result of that expression. This is why the return value of our arrow function is the passed-in parameter plus one, even though there is no “return” statement.

Example # 2 A

Example # 2 B

 

In Example # 2A, the return value of addOne(2) is: “undefined”. This happens because the function body of addOne has curly braces, but we have not explicitly returned a value. So, just as with any function in JavaScript, a function that does not specify a return value returns “undefined” (the exception to this rule is a constructor function, which can return any object but returns the instance object when no return value is specified).

In Example # 2B, we get the expected behaviour because we specify a return value.

Returning an Object in a Single-Expression Function Body

One of the main benefits of arrow function is the terse syntax. While multi-expression function bodies are perfectly acceptable, it is likely that in many cases, you’ll want to leverage that streamline single-expression (hence single-line) syntax. But what if you want to return an object in this scenario? Since the curly braces can be omitted, you simply need to wrap the object you return in parentheses.

Example # 3

In Example # 3, we’ve gone back to a single-line version of the addOne arrow function. What differs here is that the function body is wrapped in a set of parentheses. Inside of these parentheses is an object. The beauty of this approach is that the single-line version of arrow functions allows you to omit the “return” statement, so we just provide the object that we want to return in the parentheses.

Summary

This article merely scratches the surface of what is possible in ECMAScript 6 Arrow functions. But the goal here was to simply provide a gentle introduction to the syntax. The biggest changes you’ll notice right away are:

  • The order of the parameter(s) and the “function” keyword are switched.
  • The “function” keyword has been replaced by: “=>”.
  • When the function body has a single expression, no curly braces are required.
  • When the function body has a single expression, the implied return value is the expression.
  • When the function body has a single expression, an object can be implicitly returned if it is wrapped in parentheses.

In my next post, I’ll dive a bit deeper into Arrow Function parameters.

Helpful Links for ECMAScript 6 Arrow functions

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

http://wiki.ecmascript.org/doku.php?id=harmony:arrow_function_syntax

http://people.mozilla.org/~jorendorff/es6-draft.html#sec-arrow-function-definitions