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 JavaScript Array Iteration Methods Array Iteration forEach() `index` and `array` Parameters

Kieran Barker
Kieran Barker
15,004 Points

When might you use the `thisArg` parameter?

This video covers the optional index and 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?

2 Answers

Jennifer Nordell
Jennifer Nordell
Treehouse 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 undefined.

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 forEach, the this would likely refer to the object generating the event but it is implemented so that it doesn't and instead always gets undefined.

I wrote up this example and hope it helps somewhat.

let student = {
    name: 'Jennifer',
    age: 44,
    language: "JavaScript"

const button = document.getElementsByTagName('button')[0];

button.addEventListener('click', function() {
    console.log(this);  // at this point "this" refers to the button that was clicked
    Object.keys(student).forEach(function(key) {
    }, student);

Note that if you remove student as a parameter the first this still logs out the button, but the other this references result in undefined.

Hope this helps! :sparkles:

Steven Parker
Steven Parker
216,863 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.