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 trialZhenghao He
Courses Plus Student 2,389 PointsWhy 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
231,269 PointsArrow 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})`);
});
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 PointsOh , it was not taught in the lecture. Thanks :)
Steven Parker
231,269 PointsNo, that's not part of the course. I was just explaining why I used it in my example.
Elena Man
21,092 PointsThank you! I was having the same issue and didn't know where I was wrong.
Zhenghao He
Courses Plus Student 2,389 PointsZhenghao He
Courses Plus Student 2,389 Pointsoh I see, thanks!
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 PointsAakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 Points$('a').each((_,a)=>{
Why have used
_
inside each() function inplace of index ?Steven Parker
231,269 PointsSteven Parker
231,269 PointsA single underscore makes a convenient placeholder, and I use it to imply that an argument is not used.
Anthony Crespo
Python Web Development Techdegree Student 12,973 PointsAnthony Crespo
Python Web Development Techdegree Student 12,973 PointsVery helpful!