Javascript - Using Arrow Functions

Introduction

Consider the following code

$('.btn').on('click', function() { 
        var self = this; 

        setTimeout({ 
                $(self).toggleClass('btn-active'); 
        }, 1000); 
}); 

Without arrow functions, we will need to store the context in a variable.

This can be simply rewritten with arrow functions as this:

$('.btn').on('click', function() { 
        setTimeout(() => { 
                $(this).toggleClass('btn-active'); 
        }, 1000); 
}); 

Related Topic