Search code examples
javascriptsyntaxcode-documentation

How to read the documentation syntaxes?


Can someone explain how I read this syntaxes like the one below. In which I'm picking the MDN reduce method reference. I want to know what the brackets mean, why there's a comma before the words and etc.

arr.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])


Solution

  • TL;DR: The brackets indicate "optional". The commas exist to show the different function parameters. You can see the "optional" indication in the MDN documentation for each property.

    arr.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])
    
    • arr => Reduce is a function on the Array prototype: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
    • callback: The first parameter of the reduce function is a "reducer function".
      • This callback has 4 parameters, 2 of them are "optional".
      • You will accept an accumulator value as the first parameter to the callback
      • You will accept each array element as currentValue as the second parameter
      • The index and the array are in [...] to indicate they are "optional". You do not need to worry about them unless you care about the index to implement your reducer.
    • initialValue is the second "optional" value to the reduce function: A value to use as the first argument to the first call of the callback. If no initialValue is supplied, the first element in the array will be used as the initial accumulator value and skipped as currentValue. Calling reduce() on an empty array without an initialValue will throw a TypeError.