Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

arrow function with each method

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

    const url = $(this).attr('href');

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

    const url = $(this).attr('href');

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
228,039 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.