35

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.

kevinius
  • 4,232
  • 7
  • 48
  • 79
  • See also [Why “this” refers to Window in forEach in javascript?](http://stackoverflow.com/q/28708216/1048572) – Bergi Oct 28 '15 at 02:18

5 Answers5

56

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

Community
  • 1
  • 1
Tibos
  • 27,507
  • 4
  • 50
  • 64
  • 2
    That's strange. If i create a method on an object, than the 'this' value will be that object. Why is this different? – kevinius Oct 31 '13 at 13:42
  • 1
    `this` inside the body of forEach will indeed be your particular array, but there is no connection between that and the callback you provide. The callback gets invoked however the implementation of forEach wants, specifically with thisArg, window or element as this. – Tibos Oct 31 '13 at 13:53
  • Thx, i'm getting there... i used the jow array as the thisArg, but i get bad results: http://jsfiddle.net/39LSg/ . Why is that? The value of -this- seems to jump with each iteration between the window object and the jow array – kevinius Oct 31 '13 at 14:04
  • You're using the value in the array as the index of the element you want to change. First iteration changes jow[1] to 5 (replaces 2 with 5), second changes jow[5] to 5 (adds another 5 at the end), third changes jow[3] to 5 (replaces 4 with 5), every other iteration changes jow[5] to 5. – Tibos Oct 31 '13 at 14:10
  • [MDN says, In strict mode, however, **the value of _this_ remains at whatever it was set to when entering the execution** context](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this). In the context of a class method, a nested classic function passed as an argument of a forEach will keep the original class instance as the this value (given the function is not forced otherwise), sounds like arrow functions behavior doesn't it !? – Stphane Apr 09 '19 at 13:34
  • @Stphane I'm not sure i understand what you mean. If you do `[1,2,3].forEach(fn, obj)`, fn will be called 3 times equivalent to this: `fn.call(obj, 1); fn.call(obj,2); fn.call(obj, 3);`. If obj is not provided, `this` inside `fn` will resolve to the global object (not strict) or undefined (strict mode). Please note that calling `fn` creates a new execution context that has nothing to do with the execution context in which `[...].forEach(...)` was called. – Tibos Apr 10 '19 at 06:09
  • @Tibos you are right, so do I, but recently some colleague's code used a classic function as a single argument to the Array forEach method, logging _this_ value inside of it at runtime shown it was pointing to the surrounding context class instance ([instead of expected _undefined_](https://jsfiddle.net/e1a48zs0/)). This led me to wonder what was happening. In the end I suspect some Typescript transpiling stuff or webpack loader magic happening under the hood turning the fn into fat arrow fn. The MDN quote in my previous comment _«the value of "this" remains at whatever it was»_ is confusing. – Stphane Apr 10 '19 at 08:37
9

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

kevinius
  • 4,232
  • 7
  • 48
  • 79
6

If you dont pass second parameter to forEach, this will point to the global object. To achieve what you were trying to do

var jow = [5, 10, 45, 67];

jow.forEach(function(v, i, a) {
    a[i] = v + 1;
});

console.log(jow);

Output

[ 6, 11, 46, 68 ]
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
6

Inside forEach, this refers to the global window object. This is the case even if you call it from a different object (i.e. one you've created)

window.foo = 'window';

var MyObj = function(){
  this.foo = 'object';
};

MyObj.prototype.itirate = function () {
  var _this = this;

  [''].forEach(function(val, index, arr){
    console.log('this: ' + this.foo); // logs 'window'
    console.log('_this: ' + _this.foo); // logs 'object'
  });
};

var newObj = new MyObj();

newObj.itirate();
// this: window
// _this: object
vladvlad
  • 106
  • 1
  • 2
  • 4
    This is mostly true. But you can pass a `thisArg` after the callback to define what `this` refers to. In your example, you could call `[''].forEach(function (…) {…}, myObj)`, so that `this.foo` would then return `'object'` instead of `'window'`. – chharvey Aug 18 '18 at 00:13
  • 2
    And it's interesting to note that by default, the `thisArg` refers to the global `window` object (I've tested it in my browser), while in the specification it says that if no `thisArg` is provided, it should be `undefined` by default. MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach . Spec: https://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18 – chharvey Aug 18 '18 at 00:15
1

I have a very simple approach for the 'this' context question and it goes like this: whenever you want to know what is the context of 'this', check who is left to the caller if there is no caller to the left than it is the global else it is that object instance:

Examples:

let obj = { name:"test", fun:printName }

function printName(){
  console.log(this.name)
}

//who is left to the caller? obj! so obj will be 'this'
obj.fun() //test

//who is left to the caller? global! so global will be 'this'
printName() //undefined (global has no name property)

So, for the 'foreach' case when you give a callback function what actually happens in foreach implementation is something like that:

--> you call [1,2,3].foreach(callback,'optional This')

 foreach(arr,cb)
 {
  for(i=0; i<arr.len;i++)
  {
   //who is left to the caller? global! so it will be 'this'
   cb(arr[i])
  }
 }

Unless - you give it the optional 'this' or you bind the callback with a this (for example arrow function) if that happens than the called callback already has a 'this' obj which kind of 'blocks' you from changing it's given context more on bind can be found here enter link description here But basically the bind implementation look as follows:

Function.prototype.bind = function (scope) {
    var fn = this;
    return function () {
        return fn.apply(scope);
    };
}

So you can see the fn (your callback) will always be called with your 'this' (scope)

Hope it helps...

benchuk
  • 669
  • 7
  • 13