-1
array.map(function(currentValue, index, arr), thisValue)

array.filter(function(currentValue, index, arr), thisValue)

why is the use of thisValue?

luk2302
  • 55,258
  • 23
  • 97
  • 137
Vansh Bhardwaj
  • 427
  • 5
  • 9
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map *"Value to use as `this` when executing `callbackFn`"* – luk2302 Jul 16 '21 at 09:34
  • Stackoverflow is not a good place for this type of question (which is "Please provide a list of hypothetical problems that this language feature can solve"). There isn't a measurably correct answer to that type of question. – Quentin Jul 16 '21 at 09:35
  • Value to use as this when executing callbackFn, what does that really means? – Vansh Bhardwaj Jul 16 '21 at 09:37

1 Answers1

1

Because of how the this keyword works, you'd lose the context when you do something like:

array.map(this.callback)

The workaround would be:

array.map(this.callback.bind(this))

The thisValue is a more elegant way to do that:

array.map(this.callback, this)

And you can use it for your own purposes if you want, this doesn't need to be the original this:

/**
 * Accepts a callback and returns the array mapped over this callback.
 * The `this` context inside the callback will be set to someElement,
 * you can use it to influence your callback's return value.
 */
function foo(callback) {
    return array.map(callback, someElement)
}
deceze
  • 510,633
  • 85
  • 743
  • 889