ES6: Arrow functions
10min read
Arrow functions are a simpler and more concise way to declare functions which also inherit the feature to solve the “this” problem in javascript.
Arrow functions in a nutshell
Arrow functions allow us to write Functions without the function keyword and possibly even in one line. They also fix the problem with the this keyword in Javascript but more on this topic later.
ES5
Instead of writing the function keyword explicitely…
ES6
…we can now just simply leave it out and write a “=>” (fat arrow) after the parameter(s).
Too shorten it even more we can wrap the code also on one line with the return statement implicitely added.
If there is more than one parameter present we need to wrap them both in Parenthesis before the “=>” (fat arrow).
Neat code
I personally like how code with fat arrow functions looks like. It appears more neat to my “developers eye”. But judge for yourself:
ES5
This function written in ES5 syntax…
ES6
…would look like this in ES6 syntax.
The this problem
In order to understand how fat arrow functions solve the this problem lets recap first what it actually means.
When we declare a method on an object, the this keyword of that method points to the object itself.
The problem is what happens when we define another function within the object’s method that makes also use of the this keyword and run it. While the this of the outerMethod still points to the object itself, the this of the innerMethod loses its context and points to the global object (window).
Old ways (ES5) to fix it
In “the old days” we could fix that problem in multiple ways.
1. We declare in the outerMethod a new var _this and set it equal to this (reference it). From that point on we can use it as wanted in nested functions.
2. We transfer the this context of the outerMethod to the innerMethod by using bind(this) on the innerMethod.
3. We transfer the this context from the outerMethod to the innerMethod by envoking the innerMethod with call(this) or apply(this)
Fat arrow to the rescue
Fat arrow functions don’t have their own this context but instead inherit it from “where” they are defined in.
Quiz
Do you think you understood fat arrow functions? Test your knowledege with this small quiz.
Question:
What would be the value of this for both the inner and outer method if we defined the outerMethod also as a fat arrow function?
Click to show result
Result:
outer this Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
inner this Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
Since the context of the outerMethod is the global window object, the this points to the window.
Leave a Reply
Want to join the discussion?Feel free to contribute!