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.
Kieran Barker15,003 Points
When might you use the `thisArg` parameter?
This video covers the optional
array parameters for the
.forEach() method, but when might one use the optional
thisArg parameter? The MDN Web Docs say it refers to the 'Value to use as this (i.e the reference Object) when executing
callback.' But when might this actually be useful?
Jennifer NordellTreehouse Teacher
Hi there, Kieran Barker! I wondered about this, too. And what I've found out, is that if you try and use a
forEach loop and inside of it use
this, it can't work out what
this is supposed to be. So you have to tell it what
this is. Otherwise, you will get back
One specific use case I can think of is when you have a button or some other event generating element and add an event listener that then sets in motion a
forEach loop. If you were to then try and use
this inside the
this would likely refer to the object generating the event but it is implemented so that it doesn't and instead always gets
I wrote up this example and hope it helps somewhat.
Note that if you remove
student as a parameter the first
this still logs out the button, but the other
this references result in
Hope this helps!
Steven Parker210,068 Points
I assume you'd use is when you're using an existing function as a callback that internally relies on "this", so you what will be affected by the references to "this".
There's an example on the MDN forEach page.
If you're writing a new function to be used in a "forEach", you might want to specifically avoid using "this" to avoid potential confusion.