1

I'm reading through the annotated source for the Parsley javascript library, and I keep seeing notations that I don't fully understand. Google searches aren't really helping as google is ignoring "() =>" or "=>" as useful search terms.

Here's an example:

if (event) {
      this.submitEvent = $.extend({}, event, {preventDefault: () => {
        ParsleyUtils.warnOnce("Using `this.submitEvent.preventDefault()` is deprecated; instead, call `this.validationResult = false`");
        this.validationResult = false;
      }});
    }

I can guess what is happening, but I don't understand the syntax or the name of the function / lambda declaration or pattern.

What is the name of the pattern or style of function declaration? What is its purpose?

scniro
  • 15,980
  • 8
  • 54
  • 101
Kieveli
  • 10,548
  • 6
  • 48
  • 77
  • It's called "arrow function syntax" – Sergio Tulentsev Jul 27 '16 at 15:20
  • When searching stackoverflow for "javascript =>", no results matched to the answer. Hell last week I googled "when then promise" to try learning jQuery's delayed function calling, and couldn't find anything either. – Kieveli Jul 27 '16 at 15:24
  • How about `jquery deferred when` or `jquery deferred then` or `jquery promise then?` `when then promise` is very generic… – nils Jul 27 '16 at 15:25
  • There's a trick - once you know the topic, you know what to search for. Common words and operators are hard to use as search terms when you don't fully know what you need to find. – Kieveli Jul 27 '16 at 15:26
  • Oh, I figured you knew that it was jQuery's promises you were looking for. Was that not the case? – nils Jul 27 '16 at 15:28
  • By the way, the duplicate does not indicate that you did something wrong, it just means that there are already good answers to the same question. And it gives you a direct link to the answer. – nils Jul 27 '16 at 15:30

1 Answers1

4

These are referred to as arrow functions, which are basically an ES6 approach to leverage functions in a slightly new way. For some simple background on whats going on, MDN explains the idea as such

Two factors influenced the introduction of arrow functions: shorter functions and lexical this.

Check out this example...

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

with arrow syntax becomes

// `this` here is the same as `this` in the setInterval
setInterval(() => {
  this.age++; // `this` properly refers to this in the outer scope
}, 1000);

So with your example, the "traditional" representation could be as such...

var self = this;
if (event) {
  self.submitEvent = $.extend({}, event, { preventDefault: function() {
    // [...]
    self.validationResult = false;
  }});
}

Another great use of arrow functions is for one liners

[1,2,3,4].map(num => num * 2); // [2,4,6,8]
scniro
  • 15,980
  • 8
  • 54
  • 101