2

I do not understand what all these brackets mean in MDN javascript syntax document.

For example, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

in this document, there are brackets "[" between each parameter before the comma ','

Array.prototype.map()

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

but when i actually code, for example,

var numbers = [1, 4, 9];
var info = numbers.map(function(num,index) { 
    return "index: " + index + ", number: " + num;
});

console.log(info)

//output:   ["index: 0, number: 1", "index: 1, number: 4", "index: 2, number: 9"]

I do not use array or put [ in the parameters... So what does these brackets mean in the document??

enter image description here

5
  • Its an optional argument. You can ommit it. Commented Apr 6, 2018 at 13:55
  • Means optional. Commented Apr 6, 2018 at 13:55
  • @YatendrasinhJoddha incorrect Commented Apr 6, 2018 at 13:56
  • @JonasW. actually all of them are optional :) Commented Apr 6, 2018 at 13:56
  • @epascarello Ya sorry. They are optional parameters Commented Apr 6, 2018 at 13:57

1 Answer 1

7

These brackets mean optional parameters. It means, you don't have to include those parameters.

Example: Lets say I have function for incrementing: inc(x) Which needs one parameter. When called, it will increment that variable exactly by one. inc(x) equals x++ But I would like to have an option to increment by any number as well. Eg.: inx(x, 3) which gives the same result as x = x + 3. Then I can describe my function similarly as on MDN as:

function inc(variable [,increment])
Sign up to request clarification or add additional context in comments.

6 Comments

so for example, if there is a bracket, everything in [ ] are optional? or the parameter before the opening bracket?
so lets have arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue]); should it be like that : arr.reduce(callback(accumulator, currentValue[, index][, array])[, initialValue]) why array parameter in the square brackets of index, it looks like array variable is a parameter of index variable like index(array)
@O.k - It means, that array parameter can be optional, only if optional parameter index is used. You can use callback(accumulator, currentValue, index) or callback(accumulator, currentValue, index, array) But not callback(accumulator, currentValue, array) Beacuse array parameter comes to play only if index is used
@LudovitMydla - Great explanation thank you my friend
That is the reason to use double (triple, quadruple, etc) brackets in this notation: function A(mandParam1 [, optParamX [, optParamY]]) = Use optional param Y, only if previous optional param X is used
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.