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!
Callback FunctionsA callback function is a function that is passed as an argument to another function, to be “called back” at a later time. A function that accepts other functions as arguments is called a higher-order function, which contains the logic for when the callback function gets executed.
Unless otherwise specified in the description of a particular function, if a function or constructor described in this clause is given more arguments than the function is specified to allow, the extra arguments are evaluated by the call and then ignored by the function.
A callback function, is a function that is passed to another function (let's call this other function “otherFunction”) as a parameter, and the callback function is called (or executed) inside the otherFunction.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With