“forEach()” and “this”

Andrew Park
2 min readJun 18, 2021

On my last blog, I wrote about binding “this” to an “EventListener”.

I had a similar issue with defining “this” on “forEach()”.

Code below should accept an array of names (in mixed case), and return normalized names (ex. [ “anDReW”, “DAVE” ] to [ “Andrew”, “Dave” ]).

However, the error message shows that “this” is ”undefined“ (in line 13), not the instance object of normalizedName class. Why is that?

I added a “debugger” in line 13 to see who/what “this” is, and the local scope is showing “this” as “undefined”. Well, this kind of make sense since it is “nameArray.forEach” that is invoking callback function within “forEach”, not the instance object.

So, how can we fix this? There are two ways to solve this problem:

(1). If I move the “debugger” to line 12 (outside of “forEach”), and local scope shows “this” is now the instance object of class normalizeName. So, we can bind “this” to “forEach” loop.

In line 14, bind “this” (the instance object of class normalizeName) to “forEach” loop.

(2). Use arrow function within “forEach” loop:

*** And “yes”, we could have used “map” instead of “forEach”:

I know “this” can be a difficult concept to grasp. For me, finding out who/what “this” is using console.log and/or debugger always led me to right path to correct the problem.

--

--