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

Is there syntactic sugar for calling a function on each element of a list in JavaScript?

Let’s say I had the following code:

let array = [1, 2, 3]
array.forEach(x => someFunc(x))

In Java, I know the second line could be simpler using Streams (at least for static methods), like so:

array.stream().map(ClassName::someFunc) ...

Essentially I’m asking is there an analog for the ClassName::someFunc part in JavaScript, instead of having to write x => someFunc(x)?

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

>Solution :

In the simplest case, you can replace

array.forEach(x => someFunc(x))

with just

array.forEach(someFunc)

but there’s some fine print you should be aware of:

  • this generally doesn’t work with object methods: .forEach(someObj.someMeth) won’t work

  • the callback should accept exactly one argument or conform to the forEach calling convention callback(element, index, this). For example, array.map(parseInt) won’t work either, because parseInt has its own idea of what the second argument means.

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