Hacker News new | ask | show | jobs
by pekk 4012 days ago
Just eliminating the words "function" and "return" doesn't make the code clearer. Anyone competent with Javascript can easily read the first form. The difference in time to read the expression may not even be measurable. If you want to argue that it makes the code neater that's fine, but the meaning is not made clearer by the substitution of sigils for words.
2 comments

> Anyone competent with Javascript can easily read the first form

And anyone competent with any language implementing map can easily read:

    users.map(user => user.name);
...without having to do any "skimming over" the noise. It's not a big difference, you're right, but it's the kind of little thing that, when you let it build up over time, gives you the "write-everything-in-triplicate" feel of Java 6.

Further, you have to be intimately familiar with Javascript to understand why this is necessary:

    function fetchUserData(){
        var self = this;
        userService.fetchAllUsers()
                   .then(function(fetchedUsers){ self.users = fetchedUsers; });
    }
or even this:

    function fetchUserData(){
        userService.fetchAllUsers()
                   .then(function(fetchedUsers){ this.users = fetchedUsers; }.bind(this));
    }
as opposed to simply writing:

    function fetchUserData(){
        userService.fetchAllUsers()
                   .then(fetchedUsers => this.users = fetchedUsers);
    }
Did you know you can do this!?

  someObject.foo = function() {
    someObject.bar = 123;
  }

  function Foo() {
    var Foo = this;
    Foo.bar = 456;
  }
Pro tip: Always do asynchronous operations Before presenting the object to the program state. Or you will see "undefined" bugs in production!
As has been pointed out though, that is not the primary thing that arrow functions give you. They're really there to avoid having to manually bind functions in order to maintain execution context or use the old `var self = this; function(){/.../}` workaround.