I just launched a new course on ES6! Use the code WESBOS for $10 off.

Strengthen your core JavaScript skills and master all that ES6 has to offer. Start Now →

Understanding ES6 Arrow Functions for jQuery Developers

Arrow functions are a really handy new part of the ES6 JavaScript spec.

Along with shorter, more concise syntax one of the benefits is that is handles the keyword this a little differently. More specifically, it doesn’t change the binding of this when you enter into a new function that was declared with an arrow.

So, while you’ll use this in any of your JavaScript, here is a problem we have all run into with jQuery events, and how you can fix it with ES6 arrow functions.

    // Go from this code:
    $('.cta').on('click',function() {
      var that = this;
      setTimeout(function() {
      }, 1000)

    // To this code:
    $('.cta').on('click',function() {
      setTimeout(()=> {
      }, 1000)

This entry was posted in JavaScript, jQuery. Bookmark the permalink.

2 Responses to Understanding ES6 Arrow Functions for jQuery Developers

  1. I’m trying to fully wrap my mind around `this` with respect to closures. Does the `this` change referent because the closure is the param to `setTimeout`, or does `this` ALWAYS change referent inside a function, whether a closure or a named function?

  2. Ryan says:

    Great article!

    Where can I find that editor theme?
    I use vsCode

Leave a Reply

Your email address will not be published. Required fields are marked *