Hacker News new | ask | show | jobs
by phs2501 4022 days ago
Verbosity is not clarity.

    list.map(function(x) { return x * 2; });
verses

    list.map(x => x * 2);
The actual functionality of the first is swallowed in visual noise (function, return). Yes, it's something new to learn for Javascript programmers, but it's useful and makes the meaning of code clearer.

That's not even touching on the this-binding element, which is also incredibly useful in common Javascript code.

1 comments

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.
> 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.