Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does isArray not work with brackets in other method?

function steamrollArray(arr) {
  const flat = [].concat(...arr);
  return flat.some(Array.isArray) ? steamrollArray(flat) : flat;
}
function steamrollArray(arr) {
  const flat = [].concat(...arr);
  return flat.some(Array.isArray()) ? steamrollArray(flat) : flat;
}

Why does isArray not work with brackets and in which cases are no brackets required for methods?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This has nothing to do with isArray and everything to do with the difference between a function reference and calling a function.

Look closely at what this code does:

flat.some(Array.isArray)

This passes a function reference to .some(). That function will be invoked on every member of the flat array and the results of having invoked that function will be used by .some() to return its result.

Compare that with what this code does:

flat.some(Array.isArray())

This calls Array.isArray() immediately and passes its result (which is simply false because no array was provided) to .some(). That result will then fail to be called on any member of the flat array, because false is not a callable function.

in which cases are no brackets required for methods?

It all depends in whether you want to invoke the function right now or pass the function along to something else to invoke it later. Parentheses are used to invoke the function.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading