Tuesday, March 8, 2016

JavaScript: Function, Fat Arrow, Decorative Combinators, and This

In JavaScript there are now two ways to declare a function:

var myFunc = function(arguments) { ... }

and

var myFunc = (arguments) => { ... }

Now I have heard various people talk about the addition of the second pattern, fat arrow, to the language. I have heard some people imply that it is cosmetic, but this is not the case at all. Using one or the other can have drastic impacts on how your code behaves. Strangely, sometimes the difference has absolutely NO impact on how your code behaves. This is because when running the function the keyword "this" will mean something different in the two cases and if you don't use "this" there will be difference.

The other thing I have heard people say is that using fat arrow makes your functions behave like you think they should. This is kind of true, but it is not a good explanation at all. Here is my attempt to provide a good explanation:

Fat Arrow has "this" from the context the function is defined in while Function has "this" from the context the function is run in.

The difficulty of the above statement is that the context the function runs in if often not what you would expect.

This does, however, mean that both are useful. When I first started using fat arrow I thought that it should be used almost exclusively, but that was because of the style of code I was writing. When I started writing more combinators (functions that return functions) I ended up using the function keyword a lot, because the this from the context is not valid in the combinator code. I now believe that this is a subtlety that programmers should understand, but that many junior level programmers will not. This is one of the key dangers of the language. It presents itself as easy and clear, while in fact there are dangerous subtleties in how things work.

Note that for function bodies that do not use "this" the two are functionally equivalent. Many complexities can be avoided by avoided the use of "this". This is actually what Crockford recommends, although his recommendations stem from a security perspective.

No comments:

Post a Comment