0

I understand how array filter works and that the filter helper function takes a callback function that takes one mandatory argument (element) and two optional ones (index, array). However, it's confusing to understand this based on how the MDN documentation describes it:

let newArray = arr.filter(callback(element[, index, [array]])[, thisArg])

It seems as if it would be more clear if it was just:

let newArray = arr.filter(callback(element, index, array), thisArg)

Questions that I have regarding the way MDN has it are:

  1. element is the first argument to the callback followed by an array without a comma separating the two, why is this?
  2. Why is index and [array] nested within another array?
  3. What is the significance of the comma that this array starts with?
  • The square brackets here are nothing to do with arrays. It's just a standard way of denoting optional arguments. If it was written the way you claim to prefer, it wouldn't be obvious that the method behaves quite sensibly if those arguments aren't provided. – Robin Zigmond Jun 24 '20 at 16:37
  • It's admittedly kind of confusing, but documentation has used that standard for optional arguments for a very long time now. Earlier than the conception of JavaScript. – user120242 Jun 24 '20 at 16:38
  • Got it, why do the square brackets start with a comma? – Lightspeed1212 Jun 24 '20 at 16:39
  • That's just further notation for specifying optional arguments, it's as if to say f(a[, b]) could be called as f(a) or f(a, b) – richytong Jun 24 '20 at 16:40
  • 1
    meaning that it's optional. If you were to delete the characters inside the brackets, you'd get the valid prototype representation of the function call. Also happens help to differentiate it from array literal syntax. – user120242 Jun 24 '20 at 16:40
  • Maybe someone can do a write-up with the historical context. I remember seeing a decent one over in react issues on the documentation, where someone complained about this notation being confusing. – user120242 Jun 24 '20 at 16:43
  • Thanks all for clarifying. Though it makes better sense, still feel that the syntax can be updated to be more user friendly or explained by MDN for those not familiar with it. – Lightspeed1212 Jun 24 '20 at 16:43

0 Answers0