I\'m newbie in Javascript. And I faced the following question.
As stated here, almost all ES5 Array functions (forEach, map, filter, every, some) can take additional
It's simple. In the callback function, the this
value will be the second argument passed to the array method. If you won't use this
, then the argument is irrelevant and you don't need to pass it.
"use strict";
[0].forEach(function(currentValue, index, arr) {
console.log(this); // 1234
}, 1234);
Note that in sloppy mode, the this
value is converted to an object. So if you omit the argument or use undefined
, you will get the global object instead.
If you need something similar with reduce
, then use bind
:
"use strict";
[0, 1].reduce(function(prevValue, currValue, index, arr) {
console.log(this); // 1234
}.bind(1234));