4
arr.filter(callback[, thisArg])

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

So, this is the example in the documentation that I am supposed to understand.

Arr = some array, great. filter = a method the array has, great. callback = some function, basically. Great. What is [, thisArg]though?

Looking at some example on stackoverflow shows this:

objects.filter(function (obj) {
  return obj.someIntProp <= 1000 
});

I understand how this works, I don't need help using it. I just want to understand how [, thisArg] is supposed to tell me that the function takes each object in an array. I feel like I am missing something obvious that most people get taught in Coding 101.

Community
  • 1
  • 1
VSO
  • 11,546
  • 25
  • 99
  • 187

2 Answers2

5

The thisArg parameter is optional. If you pass it, then when the runtime invokes your callback, it'll set this to whatever that value is.

It's not useful in very many situations, but it's one of those things that is handy when you do want it. An alternative of course would be to bind the callback to whatever you'd pass for thisArg.

The MDN site by convention uses the [, thisArg] notation to mean that the parameter is optional.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Thank you for the reply. So this is a MDN convention, not a general coding convention? So I read this as "The function takes a callback, which can optionally take a parameter"? Why is it optional, don't we need the object to filter it? Sorry, I know I am missing something completely obvious, but have to type it out to show just how much I am missing something. – VSO Feb 02 '16 at 00:33
  • The function `.filter()` can take either one parameter - the callback - or two parameters - the callback, and the value to use as `this` when the callback is invoked. The callback itself is passed *three* parameters when it's invoked: the array element itself, the index, and a reference to the whole array. – Pointy Feb 02 '16 at 00:35
  • Alright, I got it, thanks. I see the q got marked as duplicate, but I am glad I made it anyway, the other answers were meh. – VSO Feb 02 '16 at 00:36
2

It means that the argument is optional. You may or not pass it, the function is valid anyway. If you decide to pass it, then the word this inside that function would access the given value.

Jonas Meinerz
  • 612
  • 3
  • 9
  • Accepting pointy's answer because he was first, but I appreciate the reply. Upvoted. – VSO Feb 02 '16 at 00:37