9

I have a question which has bugged me for a while now.

Let's say I have the following array:

var array = [1, 2, 3]

Now I have a function similar to this:

function print(num, str) {
    console.log(str + ": " + num);
}

Is it possible to call the forEach method and pass a string to it?

// how do I pass "str"?
array.forEach(print);

Thanks!

Chris
  • 1,008
  • 2
  • 11
  • 22

3 Answers3

14

You have two options here:

Either you swap the arguments, so that str comes first. Then you can use function.bind to bind the first arguments of the function:

function print(str, num) {
    console.log(str + ": " + num);
}

array.forEach(print.bind(null, 'someStr'));

Alternatively, you can also create a new (anonymous) function which simply passes some value to the second argument:

array.forEach(function (item) { print(item, 'someStr'); });

With ES6 and the arrow functions, this even gets a bit prettier:

array.forEach(item => print(item, 'someStr'));

Both solutions have a very similar effect in that they create a new function object which is then passed to forEach. What makes more sense to you depends on your use cases.

And just as a note: You just need to remember that the callback passed to forEach actually takes up to three arguments (the item, the item’s index, and the array itself), so be careful when you pass a function that accepts other additional arguments. You can again use a local function to remedy that.

poke
  • 369,085
  • 72
  • 557
  • 602
  • For those looking at this, wondering how to get the index as well as a parameter, plus the additional parameter, here you go: array.forEach((item, index) => print(item, index, 'someStr')); You would also have to add the index parameter to the print function declaration: function print(item, index, str) {... – Millar248 Oct 30 '19 at 16:42
5

Not in this particular situation. The simple solution here is to use an anonymous function wrapper:

array.forEach(function (i) { print(i, str); });

If you reversed the parameters to print, you could do this a little more elegantly like so:

function print(str, num) { .. };

array.forEach(print.bind(null, str));

str will be bound as the first parameter, any parameters that forEach passes when invoking the callback are passed in second, third etc. place.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 1
    FWIW: That second option is sometimes called *partial application* or *currying* (after [Haskell Curry](https://en.wikipedia.org/wiki/Haskell_Curry)) in the functional programming world. – T.J. Crowder Feb 15 '16 at 10:28
1

Here you go

var array = [1, 2, 3];

function print(str, num) {
    console.log(str + ": " + num);
}

var str = 'someString';
array.forEach(print.bind(null, str));