1

Sometimes I study Javascript code in MDN, but I don't understand what's the meaning of [, thisArg] things... for example,

arr.map(callback(currentValue[, index[, array]])[, thisArg])

in this case, I know about there needs to be have callback Function. but what's that in the square brackets? why they need comma in case of there's nothing in front of?

Jay
  • 63
  • 6

1 Answers1

1

It means that whatever is in the brackets is an optional argument. If you do use an additional optional argument, you need a comma to separate it from the previous argument.

The notation

arr.map(callback(currentValue[, index[, array]])[, thisArg])

perhaps more easily read as

arr.map(
  callback(currentValue[, index[, array]])
  [, thisArg]
)

means that the callback can accept 1, 2, or 3 arguments, and that .map accepts the callback as the first argument, and can optionally accept a second argument (the thisArg) as well.

As Kaiido notes, in the specific case of Array.prototype.map, the currentValue is actually optional as well, it's just extremely odd to use .map without using any of the arguments:

const arr = [3, 4];
const newArr = arr.map(() => 999);
console.log(newArr);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • oh, then [, this means just an option in this bracket] right? – Jay Jun 13 '19 at 07:45
  • It means that what is inside the bracket is an optional argument. – CertainPerformance Jun 13 '19 at 07:46
  • But to be fair, even `currentValue` can be optional here... We are the author of `callback`... Not sure why they did set these square brackets... The ones for `thisArg` make sense though. – Kaiido Jun 13 '19 at 07:53