Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
215,959 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.