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! While you're at it, check out some resources Treehouse students have shared here.
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 trialAdam Lyles Kauffman
14,016 Pointsarrow 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
231,269 PointsYou 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.