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

Kieran Barker
Kieran Barker
15,028 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
228,978 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.