Hacker News new | ask | show | jobs
by Kiro 4181 days ago
I don't understand the benefit of fat arrow. I actually think it decreases the readability. What does lexical "this" binding mean?
3 comments

Fat arrow notation massively increases readibility by reducing the boilerplate verbosity of function definitions. Lexical "this" binding means that the "this" of the enclosing scope is reused; Arrow-defined functions do not get their own "this" when they are called.
Thanks but massively? function() {} vs () => {}?
Also removes return statement for 1 liners. Reduces clutter of anon functions, especially when you're chaining a bunch together

e.g.

ES5

    users.map(function(user) {
      return user.name
    }).filter(function(name) {
      return name.length < 30
    }).sort(function(a, b) {
      return a.length - b.length
    })
vs

ES6

    users
    .map(user => user.name)
    .filter(name => name.length < 30)
    .sort((a, b) => a.length - b.length)
Contrived, but typical example.
More like:

    var _this = this;
    call(function (){
        return _this.value;
    });
versus

    call(() => this.value);
So yeah, much more readable, and less issues with this binding to some other caller or window.
It's more like

    function(){}.bind(this)


 vs

    () => {}
And for a single expression the `{}` are optional and a `return` is implied, which is pretty nice for .map()/.sort(), etc.

Automatically bound `this` is super important. It's very easy to forget one `.bind(this)` (or `that` alias) somewhere, especially when you have several levels of callback nesting.

It means it inherits the 'this' of the enclosing function.

Without fat arrow: function outer() { function inner() { this === inner.this; } }

With fat arrow: function outer() { var inner = => this === outer.this; }

A lot of times you stuff the context (this) into a variable (like that)... so that you can use it in callback handlers farther down.

Fat arrow syntax is much more terse than a function declaration and also handles the case of passing the parent's execution scope.