Understanding ES6 Arrow Functions for jQuery Developers

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() {
        $(that).toggleClass('on');
      }, 1000)
    });

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

https://youtu.be/6aETKj5-SKg

Find an issue with this post? Think you could clarify, update or add something?

All my posts are available to edit on Github. Any fix, little or small, is appreciated!

Edit on Github

Syntax Podcast

Hold on — I'm grabbin' the last one.

Listen Now →
Syntax Podcast

@wesbos Instant Grams

Beginner JavaScript

Beginner JavaScript

A fun, exercise heavy approach to learning Modern JavaScript from scratch. This is a course for absolute beginners or anyone looking to brush up on their fundamentals. Start here if you are new to JS or programming in general!

BeginnerJavaScript.com
I post videos on and code on

Wes Bos © 1999 — 2024

Terms × Privacy Policy