Comma in front of square bracket - MDN docs

Viewed 164

MDN is my primary Javascript resource. I often see a notation like ( currentValue[, index[, array]]) as in:

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

I'm surprised there's a square bracket in front of the comma. It looks like an invalid syntax to me.

I would highly appreciate it if somebody could give more information about this notation.

3 Answers

The square brackets mean that the enclosed parameter is optional.

Refer MDN syntax section for more info.

That means the callback requires a currentValue as the first argument, and index and array are optional arguments.

It is an invalid JS syntax, and it would throw an error.

However, it is used to denote optional arguments as a pseudo-code.

The parts in the square brackets are considered optional (and in the real code the brackets should be omitted), so, you might call this function like:

let new_array = arr.map(function callback(currentValue) {
    // return element for new_array
})
//or
let new_array = arr.map(function callback(currentValue) {
    // return element for new_array
}, thisArg)
//or
let new_array = arr.map(function callback(currentValue, index) {
    // return element for new_array
})
//or
let new_array = arr.map(function callback(currentValue, index) {
    // return element for new_array
}, thisArg)
//or
let new_array = arr.map(function callback(currentValue, index, array) {
    // return element for new_array
})
//or
let new_array = arr.map(function callback(currentValue, index, array) {
    // return element for new_array
}, thisArg)

and each of them is valid.

Related