Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The invocation context (this) of the forEach function call

I was wondering what the 'this' value (or invocation context) is of the forEach callback function. This code doesn't seem to work:

var jow = [5, 10, 45, 67];  jow.forEach(function(v, i, a){      this[i] = v + 1;  });  alert(jow); 

Thx for explaining it to me.

like image 447
kevinius Avatar asked Oct 31 '13 13:10

kevinius


People also ask

What does the forEach function do?

forEach() The forEach() method executes a provided function once for each array element.

What is array prototype forEach call?

Description. forEach() executes the provided callback once for each element present in the array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized (i.e. on sparse arrays). callback is invoked with three arguments: the element value.

What is forEach loop in JavaScript?

The forEach method passes a callback function for each element of an array together with the following parameters: Current Value (required) - The value of the current array element. Index (optional) - The current element's index number. Array (optional) - The array object to which the current element belongs.


2 Answers

MDN states:

array.forEach(callback[, thisArg])

If a thisArg parameter is provided to forEach, it will be used as the this value for each callback invocation as if callback.call(thisArg, element, index, array) was called. If thisArg is undefined or null, the this value within the function depends on whether the function is in strict mode or not (passed value if in strict mode, global object if in non-strict mode).

So in short, if you only provide the callback and you're in non-strict mode (the case you presented), it will be the global object (window).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

like image 190
Tibos Avatar answered Oct 06 '22 02:10

Tibos


I finished construction of the forEach method and wanted to share this diagram with everyone, hope it helps someone else trying to understand its inner workings.

The forEach method

like image 33
kevinius Avatar answered Oct 06 '22 02:10

kevinius