2

I just wanted to read a file with node.js.

I used to use this notation:

fs.readFile('/etc/passwd', function(err, data) {
  if (err) throw err;
  console.log(data);
});

Node.js’s documentation provides the following code:

fs.readFile('/etc/passwd', (err, data) => {
  if (err) throw err;
  console.log(data);
});

What's the difference between them?

Dominik
  • 35
  • 6

3 Answers3

6
  • Arrow functions are new in ES6, so they aren't supported in older browsers.

  • Arrow functions have lexical this.

    this.foo = 'bar';
    
    baz(function() {
        this.foo // probably undefined
    });
    
    baz(() => {
        this.foo // == 'bar'
    });
    
josh3736
  • 139,160
  • 33
  • 216
  • 263
  • …and [more](http://stackoverflow.com/q/32535110/1048572) – Bergi Feb 22 '16 at 22:17
  • josh and the other ones answered my question more clearly. My question is a bit more specific about the difference of those two notations. If I would only know what a arrow function (a phrase I just learned from these answers here) is I wouldn't know that there is no (practical) difference (for me). – Dominik Feb 22 '16 at 22:31
  • yeah, if you don't need `this` for a method or `arguments.callee` (or `fn.name`) to do recursion, they are interchangeable. – dandavis Feb 22 '16 at 22:54
0

=> is es6 notation. Arrow functions are ALWAYS anonymous. The two pieces of code you gave will function the same.

UdaraW
  • 98
  • 1
  • 8
-4

The second is ECMA 6, the first is a bit older. There's no difference.

djechlin
  • 59,258
  • 35
  • 162
  • 290