Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: How to pass extra parameters to a callback [duplicate]

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!

like image 295
Chris Avatar asked Feb 15 '16 10:02

Chris


People also ask

Can a callback function have arguments?

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.

What happens if you pass an extra parameter to a method in JavaScript?

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.

What is callback in JavaScript stack overflow?

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.


1 Answers

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.

like image 53
poke Avatar answered Nov 14 '22 23:11

poke