Home > Software engineering >  What is the use of ,[] in an anonymous function called?
What is the use of ,[] in an anonymous function called?

Time:08-15

I was doing a coding challenge which takes in either a one or two dimensional array and then returns a flattened array. After writing my code I looked on the forums to see how others wrote theirs and found an interesting answer.

function flattenArray(array) {
  return array.reduce((acc, cur) => acc.concat(cur), []);
}

Note at the end of the return line, he used ,[] after the concat. I tried to break it down to see if I could understand that last part but I am unable to throw {} around it without it throwing me an error.

function quickFlatten(array)
{
  return array.reduce((acc, cur) => {
  acc.concat(cur), [];
  });
}

When this is called I am given a TypeError:

TypeError: acc.concat is not a function

What is ",[]" , how does it work and how can I learn more about what he did? It appears to make acc an array but only works when there are no {} in the anonymous function.

CodePudding user response:

This is the initial value of the accumulator (called acc here) use by the reduce function.

Reduce builds up a value by iterating over an array and returning it for the next iteration. The initial value has to come from somewhere, and it comes as a second parameter of the reduce function :)

you should probably read this : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

  • Related