Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding 'arr.filter(callback[, thisArg])' Syntax [duplicate]

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.

like image 382
VSO Avatar asked Mar 14 '23 10:03

VSO


1 Answers

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.

like image 139
Pointy Avatar answered Mar 27 '23 17:03

Pointy