Throw out problem

We often see this notation for fn(a[, b]) in documentation, and we’re sure to say, “This represents an optional parameter, which means you can write or you can’t write.”

That’s what I thought at first, but when I looked at the Node documentation, I got a little confused. For example:

Buffer.alloc(size[, fill[, encoding]])

buf.includes(value[, byteOffset][, encoding])

buf.write(string[, offset[, length]][, encoding])
Copy the code

To sum up:

  • fn(a, [b [, c]])

  • fn(a [, b] [, c])

  • fn(a, [b, c])

What’s the difference between these three?

Are you confused at this point?

Now, what are we to make of []?

To check

Therefore, I began to find out where the meaning [] represents comes from. Is there a special document specification to define it?

Tracing back to the source, I find that the definition of [] comes from a grammar called Bacos paradigm. This link comes from Baidu Encyclopedia, but it does not introduce specific grammar rules. See this blog post for more details.

Maybe the rules are so complicated to describe in words that I don’t really understand what they mean…

To solve the problem

After my deep reflection, I finally found a way to explain the above three examples.

You are only free to remove or keep a whole square bracket, not to tear it apart.

Fn (a, [b [, c]]), [b [, c]], this whole thing is optional, that is, b and C are optional. Then we remove the outer [], which becomes B [, C], which means that B is required for C. To sum up, both B and C are optional, but c can be passed in or omitted freely only after passing IN B.

Fn (a [, b] [, c]) b and c are independent parameters and do not depend on each other. B (or C) can be passed in (or omitted) alone.

[a, [b, c]] [b, c] [b, c] [b, C]

conclusion

I can’t believe a square bracket has such a deep hole.

This article is formatted using MDNICE