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.