I was looking at the class Buffer for the method Buffer.alloc() and the documentation has this as the method declaration Buffer.alloc(size[,fill[,encoding]]) and i am confused on what the parameter should be. I come from c++/c/java/c# and the syntax is throwing me off i dont know what size[,fill[,encoding]] is supposed to represent? An array? What is the comma for? Why are these nested? Why is there empty slots? I have looked and cant seem to find an explanation or tutorial? Is this a Node.js specific or is this a JavaScript thing?
3 Answers
The square bracket notation is from Extended Backus-Naur Form, and indicates that the enclosed parameters are optional.
size[,fill[,encoding]] means that the size parameter is required, but fill and encoding (including the preceding commas) are optional. Also, it means that encoding can only be specified if fill is specified.
Comments
Quoting this answer:
Square brackets mean the thing inside them is optional – either you have it or you don't. It is a concise way of listing the valid invocation forms.
In your case, the square brackets mean that there are 3 signatures:
Buffer.alloc(size )
Buffer.alloc(size, fill )
Buffer.alloc(size, fill, encoding)
Hint
The examples I make deliberately omit parameters for the sake of readability. Whenever you see something like a(b, , ,), imagine there's an undefined or null in between commas without values, so a(b, undefined, undefined, undefined).
Simple Example
Another example could look like this:
example(alpha, [, beta], [, gamma], delta)
... which means the following signatures will work:
example(alpha, , , delta)
example(alpha, , gamma, delta)
example(alpha, beta, , delta)
example(alpha, beta, gamma, delta)
Nesting
In your case, Buffer.alloc(size[,fill[,encoding]]), the encoding parameter must only be provided when the fill parameter is provided as well because encoding is nested in the square brackets around fill. So, the following is invalid:
Buffer.alloc(size, , encoding).
Multiple Nested Params
Multiple parameters can be nested in one level of brackets too:
example2(alpha, [, beta, gamma] [,delta])
... which means these calls are valid:
example2(alpha, beta, gamma, )
example2(alpha, , , )
example2(alpha, beta, gamma, delta)
example2(alpha, , , delta)
... while these are invalid:
example2(alpha, beta, , )
example2(alpha, , gamma, )
example2(alpha, beta, , delta)
example2(alpha, , gamma, delta)
Where to find this notation
As @cybersam said in his answer, this notation is called Extended Backus-Naur. It can also be found in a lot of man pages, the jQuery docs and many other documentations.
2 Comments
Arguments in square brackets in documentation typically just mean "this part is optional". In the case of Buffer.alloc, it means that you can call it in three ways:
Buffer.alloc(size)
Buffer.alloc(size, fill)
Buffer.alloc(size, fill, encoding)
The brackets are not actual JavaScript, but are just commonly used to describe this in documentation.