Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'this' is undefined inside the foreach loop

I am writing some typescript code and iterating an array. Inside the loop, I am trying to access 'this' object to do some processing as:

console.log('before iterate, this = ' +this); myarray.days.forEach(function(obj, index) {     console.log('before transform, this : ' + this);     this.datePipe.transform... }); 

but this fails, as it complains that 'this' is undefined 'this' object prints correctly as [object object] before/outside the loop, but inside the loop, it is undefined. Why is that? And what is the fix for that?

like image 917
user1892775 Avatar asked May 01 '17 18:05

user1892775


People also ask

Why is forEach undefined?

The "Cannot read property 'forEach' of undefined" error occurs when calling the forEach method on an undefined value. To solve the error make sure to initialize the variable to the correct value and only call the forEach method on the correct data type.

Does forEach always return undefined?

forEach() executes the callbackFn function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable.

What is forEach function in JavaScript?

The forEach() method calls a function for each element in an array. The forEach() method is not executed for empty elements.


1 Answers

You need to either use an arrow function:

myarray.days.forEach((obj, index) => {     console.log('before transform, this : ' + this);     this.datePipe.transform... }); 

Or use the bind method:

myarray.days.forEach(function(obj, index) {     console.log('before transform, this : ' + this);     this.datePipe.transform... }.bind(this)); 

The reason is that when passing a regular function as a callback, when it is invoked the this is not actually preserved.
The two ways which I mentioned above will make sure that the right this scope is preserved for the future execution of the function.

like image 100
Nitzan Tomer Avatar answered Oct 05 '22 08:10

Nitzan Tomer