With () => {}
and function () {}
we are getting two very similar ways to write functions in ES6. In other languages lambda functions often distinguish themselves by being anonymous, but in ECMAScript any function can be anonymous. Each of the two types have unique usage domains (namely when this
needs to either be bound explicitly or explicitly not be bound). Between those domains there are a vast number of cases where either notation will do.
Arrow functions in ES6 have at least two limitations:
new
and cannot be used when creating prototype
this
bound to scope at initialisationThese two limitations aside, arrow functions could theoretically replace regular functions almost anywhere. What is the right approach using them in practice? Should arrow functions be used e.g.:
this
variable and we are not creating an object.I am looking for a guideline to selecting the appropriate function notation in the future version of ECMAScript. The guideline will need to be clear, so that it can be taught to developers in a team, and to be consistent so that it does not require constant refactoring back and forth from one function notation to another.
The question is directed at people who have thought about code style in the context of the upcoming ECMAScript 6 (Harmony) and who have already worked with the language.
When you should use them. Arrow functions shine best with anything that requires this to be bound to the context, and not the function itself. Despite the fact that they are anonymous, I also like using them with methods such as map and reduce , because I think it makes my code more readable.
Arrow functions introduce concise body syntax, or implicit return. This allows the omission of the curly brackets and the return keyword. Implicit return is useful for creating succinct one-line operations in map , filter , and other common array methods.
Arrow functions are best for callbacks or methods like map, reduce, or forEach. You can read more about scopes on MDN. On a fundamental level, arrow functions are simply incapable of binding a value of this different from the value of this in their scope.
It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.
A while ago our team migrated all its code (a mid-sized AngularJS app) to JavaScript compiled using Traceur Babel. I'm now using the following rule of thumb for functions in ES6 and beyond:
function
in the global scope and for Object.prototype
properties.class
for object constructors.=>
everywhere else.Why use arrow functions almost everywhere?
thisObject
as the root. If even a single standard function callback is mixed in with a bunch of arrow functions there's a chance the scope will become messed up.function
immediately sticks out for defining the scope. A developer can always look up the next-higher function
statement to see what the thisObject
is.Why always use regular functions on the global scope or module scope?
thisObject
.window
object (global scope) is best addressed explicitly.Object.prototype
definitions live in the global scope (think String.prototype.truncate
, etc.) and those generally have to be of type function
anyway. Consistently using function
on the global scope helps avoid errors.function foo(){}
than const foo = () => {}
— in particular outside other function calls. (2) The function name shows in stack traces. While it would be tedious to name every internal callback, naming all the public functions is probably a good idea.Attempting to instantiate an arrow function throws an exception:
var x = () => {}; new x(); // TypeError: x is not a constructor
One key advantage of functions over arrow functions is therefore that functions double as object constructors:
function Person(name) { this.name = name; }
However, the functionally identical2 ECMAScript Harmony draft class definition is almost as compact:
class Person { constructor(name) { this.name = name; } }
I expect that use of the former notation will eventually be discouraged. The object constructor notation may still be used by some for simple anonymous object factories where objects are programmatically generated, but not for much else.
Where an object constructor is needed one should consider converting the function to a class
as shown above. The syntax works with anonymous functions/classes as well.
The probably best argument for sticking to regular functions - scope safety be damned - would be that arrow functions are less readable than regular functions. If your code is not functional in the first place, then arrow functions may not seem necessary, and when arrow functions are not used consistently they look ugly.
ECMAScript has changed quite a bit since ECMAScript 5.1 gave us the functional Array.forEach
, Array.map
and all of these functional programming features that have us use functions where for loops would have been used before. Asynchronous JavaScript has taken off quite a bit. ES6 will also ship a Promise
object, which means even more anonymous functions. There is no going back for functional programming. In functional JavaScript, arrow functions are preferable over regular functions.
Take for instance this (particularly confusing) piece of code3:
function CommentController(articles) { this.comments = []; articles.getList() .then(articles => Promise.all(articles.map(article => article.comments.getList()))) .then(commentLists => commentLists.reduce((a, b) => a.concat(b))); .then(comments => { this.comments = comments; }) }
The same piece of code with regular functions:
function CommentController(articles) { this.comments = []; articles.getList() .then(function (articles) { return Promise.all(articles.map(function (article) { return article.comments.getList(); })); }) .then(function (commentLists) { return commentLists.reduce(function (a, b) { return a.concat(b); }); }) .then(function (comments) { this.comments = comments; }.bind(this)); }
While any one of the arrow functions can be replaced by a standard function, there would be very little to gain from doing so. Which version is more readable? I would say the first one.
I think the question whether to use arrow functions or regular functions will become less relevant over time. Most functions will either become class methods, which make away with the function
keyword, or they will become classes. Functions will remain in use for patching classes through the Object.prototype
. In the mean time I suggest reserving the function
keyword for anything that should really be a class method or a class.
extend
keyword. A minor difference is that class declarations are constants, whereas function declarations are not.According to the proposal, arrows aimed "to address and resolve several common pain points of traditional function expressions". They intended to improve matters by binding this
lexically and offering terse syntax.
However,
this
lexicallyTherefore, arrow functions create opportunities for confusion and errors, and should be excluded from a JavaScript programmer's vocabulary, replaced with function
exclusively.
this
this
is problematic:
function Book(settings) { this.settings = settings; this.pages = this.createPages(); } Book.prototype.render = function () { this.pages.forEach(function (page) { page.draw(this.settings); }, this); };
Arrow functions intend to fix the problem where we need to access a property of this
inside a callback. There are already several ways to do that: One could assign this
to a variable, use bind
, or use the third argument available on the Array
aggregate methods. Yet arrows seem to be the simplest workaround, so the method could be refactored like this:
this.pages.forEach(page => page.draw(this.settings));
However, consider if the code used a library like jQuery, whose methods bind this
specially. Now, there are two this
values to deal with:
Book.prototype.render = function () { var book = this; this.$pages.each(function (index) { var $page = $(this); book.draw(book.currentPage + index, $page); }); };
We must use function
in order for each
to bind this
dynamically. We can't use an arrow function here.
Dealing with multiple this
values can also be confusing, because it's hard to know which this
an author was talking about:
function Reader() { this.book.on('change', function () { this.reformat(); }); }
Did the author actually intend to call Book.prototype.reformat
? Or did he forget to bind this
, and intend to call Reader.prototype.reformat
? If we change the handler to an arrow function, we will similarly wonder if the author wanted the dynamic this
, yet chose an arrow because it fit on one line:
function Reader() { this.book.on('change', () => this.reformat()); }
One may pose: "Is it exceptional that arrows could sometimes be the wrong function to use? Perhaps if we only rarely need dynamic this
values, then it would still be okay to use arrows most of the time."
But ask yourself this: "Would it be 'worth it' to debug code and find that the result of an error was brought upon by an 'edge case?'" I'd prefer to avoid trouble not just most of the time, but 100% of the time.
There is a better way: Always use function
(so this
can always be dynamically bound), and always reference this
via a variable. Variables are lexical and assume many names. Assigning this
to a variable will make your intentions clear:
function Reader() { var reader = this; reader.book.on('change', function () { var book = this; book.reformat(); reader.reformat(); }); }
Furthermore, always assigning this
to a variable (even when there is a single this
or no other functions) ensures one's intentions remain clear even after the code is changed.
Also, dynamic this
is hardly exceptional. jQuery is used on over 50 million websites (as of this writing in February 2016). Here are other APIs binding this
dynamically:
this
.this
.this
.EventTarget
with this
.this
.(Statistics via http://trends.builtwith.com/javascript/jQuery and https://www.npmjs.com.)
You are likely to require dynamic this
bindings already.
A lexical this
is sometimes expected, but sometimes not; just as a dynamic this
is sometimes expected, but sometimes not. Thankfully, there is a better way, which always produces and communicates the expected binding.
Arrow functions succeeded in providing a "shorter syntactical form" for functions. But will these shorter functions make you more successful?
Is x => x * x
"easier to read" than function (x) { return x * x; }
? Maybe it is, because it's more likely to produce a single, short line of code. According to Dyson's The influence of reading speed and line length on the effectiveness of reading from screen,
A medium line length (55 characters per line) appears to support effective reading at normal and fast speeds. This produced the highest level of comprehension . . .
Similar justifications are made for the conditional (ternary) operator, and for single-line if
statements.
However, are you really writing the simple mathematical functions advertised in the proposal? My domains are not mathematical, so my subroutines are rarely so elegant. Rather, I commonly see arrow functions break a column limit, and wrap to another line due to the editor or style guide, which nullifies "readability" by Dyson's definition.
One might pose, "How about just using the short version for short functions, when possible?". But now a stylistic rule contradicts a language constraint: "Try to use the shortest function notation possible, keeping in mind that sometimes only the longest notation will bind this
as expected." Such conflation makes arrows particularly prone to misuse.
There are numerous issues with arrow function syntax:
const a = x => doSomething(x); const b = x => doSomething(x); doSomethingElse(x);
Both of these functions are syntactically valid. But doSomethingElse(x);
is not in the body of b
. It is just a poorly-indented, top-level statement.
When expanding to the block form, there is no longer an implicit return
, which one could forget to restore. But the expression may only have been intended to produce a side-effect, so who knows if an explicit return
will be necessary going forward?
const create = () => User.create(); const create = () => { let user; User.create().then(result => { user = result; return sendEmail(); }).then(() => user); }; const create = () => { let user; return User.create().then(result => { user = result; return sendEmail(); }).then(() => user); };
What may be intended as a rest parameter can be parsed as the spread operator:
processData(data, ...results => {}) // Spread processData(data, (...results) => {}) // Rest
Assignment can be confused with default arguments:
const a = 1; let x; const b = x => {}; // No default const b = x = a => {}; // "Adding a default" instead creates a double assignment const b = (x = a) => {}; // Remember to add parentheses
Blocks look like objects:
(id) => id // Returns `id` (id) => {name: id} // Returns `undefined` (it's a labeled statement) (id) => ({name: id}) // Returns an object
What does this mean?
() => {}
Did the author intend to create a no-op, or a function that returns an empty object? (With this in mind, should we ever place {
after =>
? Should we restrict ourselves to the expression syntax only? That would further reduce arrows' frequency.)
=>
looks like <=
and >=
:
x => 1 ? 2 : 3 x <= 1 ? 2 : 3 if (x => 1) {} if (x >= 1) {}
To invoke an arrow function expression immediately, one must place ()
on the outside, yet placing ()
on the inside is valid and could be intentional.
(() => doSomething()()) // Creates function calling value of `doSomething()` (() => doSomething())() // Calls the arrow function
Although, if one writes (() => doSomething()());
with the intention of writing an immediately-invoked function expression, simply nothing will happen.
It's hard to argue that arrow functions are "more understandable" with all the above cases in mind. One could learn all the special rules required to utilize this syntax. Is it really worth it?
The syntax of function
is unexceptionally generalized. To use function
exclusively means the language itself prevents one from writing confusing code. To write procedures that should be syntactically understood in all cases, I choose function
.
You request a guideline that needs to be "clear" and "consistent." Using arrow functions will eventually result in syntactically-valid, logically-invalid code, with both function forms intertwined, meaningfully and arbitrarily. Therefore, I offer the following:
function
.this
to a variable. Do not use () => {}
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With