0

The MDN Web Documentation describes the syntax for use in JavaScript standard built in objects methods, using brackets to group the available parameters.

For example:

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
// Return element for new_array
}[, thisArg])

This has been causing some confusion for me while reading the documentation and I can not understand the purpose of grouping the parameters with brackets.

For instance, in the example above, why are the index and array parameters grouped as so.

callback(currentValue[, index[, array]])

Many thanks for your time and help.

R.F. Nelson
  • 2,254
  • 2
  • 12
  • 24
Sam
  • 63
  • 7

1 Answers1

0

That's an attempt to indicate that they're optional. You could do

.map(function callback(currentValue) { ... })

or

.map(function callback(currentValue, index) { ... })

or

.map(function callback(currentValue, index, array) { ... })

It's up to you and what you need in the callback.

This specific case isn't a great use of that, because your callback will always receive three arguments, regardless of how many formal parameters you declare that it accepts. But that notation, putting optional parameters in square brackets, is fairly common when indicating what a function requires vs. what's optional.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    As a relative beginner, I have been learning with video tutorials, and as such I was unaware of such a notation. This makes complete sense now. Thank you very much for the clarification! – Sam Jul 25 '18 at 17:13
  • @Sam - That's the problem with notation conventions. If you don't know them, you...don't know them. They aren't very discoverable. :-) – T.J. Crowder Jul 25 '18 at 17:52