Hemanth's Scribes

javascript

thisArg in JavaScript

Author Photo

Hemanth HM

Thumbnail

Not many are aware of thisArg that several built-in array methods have in their signature.

If a thisArg parameter is provided, it will be used as the this value for each invocation of the callback function. If not provided, undefined is used instead.

Note: If the callback is an Arrow Function, this was lexically bound when the function was created, so thisArg will have no effect.

Methods with thisArg

  • Array.from(arrayLike [, mapfn [, thisArg]])
  • Array.prototype.every(callbackfn [, thisArg])
  • Array.prototype.filter(callbackfn [, thisArg])
  • Array.prototype.find(predicate [, thisArg])
  • Array.prototype.findIndex(predicate [, thisArg])
  • Array.prototype.forEach(callbackfn [, thisArg])
  • Array.prototype.map(callbackfn [, thisArg])
  • Array.prototype.some(callbackfn [, thisArg])

Example: forEach

let jedi = {
  name: 'yoda',
  height: '66cms',
  mass: '17 kgs'
};

### Without thisArg
javascript
Object.keys(jedi).forEach(function(key) {
  console.log(jedi[key]);
});

### With thisArg
javascript
Object.keys(jedi).forEach(function(key) {
  // |this| now refers to `jedi`
  console.log(this[key]);
}, jedi); // last arg is `thisArg`

The same could be achieved with bind, but it would be slower. Check the performance comparison.

#javascript
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.