JavaScript jQuery Basics Working with jQuery Collections Looping through a jQuery collection

Adam Lyles Kauffman
Adam Lyles Kauffman
11,760 Points

arrow function with each method

my code is not executing correctly when trying to use arrow function with the keyword this:

$('a').each(()=>{ 
    const url = $(this).attr('href');
    $(this).parent().append(`(${url})`);
});

i dont understand why the following code works if i dont use the arrow function:

$('a').each(function(){ 
    const url = $(this).attr('href');
    $(this).parent().append(`(${url})`);
});

also, i know the each method works with arrow functions because this code executed fine:

//$('a').each((index, link)=>{ 
//    console.log(index, $(link).attr('href'));
//    const url = $(link).attr('href');
//    $(link).parent().append(`(${url})`);
//});

1 Answer

Steven Parker
Steven Parker
173,991 Points

You have discovered one of the ways that arrow functions and conventional functions are different. Arrow functions do not establish a value for "this" like conventional functions do.

Arrow functions are not intended to be used to replace conventional functions in all situations, and in fact there are some situations where they are specifically not allowed (they cannot be used as constructors, for example). There are other differences as well, for details see this MDN page.