Array.forEach() et al with additional parameters

Christian Mayer mail at ChristianMayer.de
Sat Dec 20 04:12:28 PST 2014


I'm just stumbling over a little improvement (syntactic sugar) that
could help to make code a bit smaller (-> less to debug, read,
understand, etc. pp.)

When you want to pass additional parameters to the Array.forEach()
callback function you currently must work with an additional (anonymous)
function that is just wrapping stuff. (And for heavily recursive stuff
cutting the useable call stack in half...)

Currently:
----------

function myCallback( element, count, array, additionalFoo )
{
  console.log( 'Callback #' + count + ': ' + element, additionalFoo );
}

[1,2,3].forEach( function( element, count, array ){
  myCallback( element, count, array, 'additionalFoo' );
});

New:
----

[1,2,3].forEach( myCallback, undefined, 'additionalFoo' );

It could be discussed whether the additions parameter is only one (and
thus the programmer has to pass multiple information in a Array or
Object) or if all additional parameters will be passed on to the
callback function.

The same holds for the similar functions "map", "every" and "some".

What do you think?


More information about the es-discuss mailing list