3

I've been pursuing the codegolf site lately with a focus on Javascript. I keep seeing something that I don't understand and can't find an answer to. Check out this answer. The first line starts with F=a=>. I assume that this is a shorthand function declaration, but I can't find any reference to it elsewhere on the web. Can someone explain, or point me to a good document about this syntax?

Feel free to tag this question. Hard to tag when I don't know what I'm looking at.

Community
  • 1
  • 1
Nate
  • 2,035
  • 8
  • 23
  • 33

2 Answers2

2

If you look at the ES6 definition document this is the Arrow function symbol

Looking at MDN's documentation this is just shorthand for declaring an anonymous function

An interesting difference is that the arrow function syntax provides a closure so (quoting from MDN)

In ECMAScript 3/5, this issue was fixed by assigning the value in this to a variable that could be closed over.

function Person() {
  var self = this; // Some choose `that` instead of `self`. 
                   // Choose one and be consistent.
  self.age = 0;

  setInterval(function growUp() {
    // The callback refers to the `self` variable of which
    // the value is the expected object.
    self.age++;
  }, 1000);
}

Alternatively, a bound function could be created so that the proper this value would be passed to the growUp function.

Arrow functions capture the this value of the enclosing context, so the following code works as expected.

function Person(){
  this.age = 0;

  setInterval(() => {
    this.age++; // |this| properly refers to the person object
  }, 1000);
}

var p = new Person();

In those two examples you can see the difference very clearly

function() {
    console.writeline('es5');
}

versus

   () => {
       console.writeline('es6');
   }
Paul D'Ambra
  • 7,629
  • 3
  • 51
  • 96
1

Yea, that is a shorthand for a function declaration.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

iamkrillin
  • 6,798
  • 1
  • 24
  • 51