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 trial

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

Why can't arrow function work in this case

Hi guys, I was following along with the video and there was this snippet

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

I tried to rewrite this by using arrow function as

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

but it didn't work. Why is that?

3 Answers

Steven Parker
Steven Parker
231,275 Points

Arrow functions are not exact replacements for conventional functions and work a bit differently. One of the differences is that arrow functions do not establish a value for "this".

See this MDN page for more information on arrow functions and how they are different.

You can usually refactor the code to use passed-in argument(s) instead of "this". In this example:

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

oh I see, thanks!

Steven Parker
Steven Parker
231,275 Points

A single underscore makes a convenient placeholder, and I use it to imply that an argument is not used.

Steven Parker
Steven Parker
231,275 Points

No, that's not part of the course. I was just explaining why I used it in my example.

Elena Man
Elena Man
21,092 Points

Thank you! I was having the same issue and didn't know where I was wrong.