How to pass multiple arguments into a JavaScript callback function?

Sometimes, we want to pass multiple arguments into a JavaScript callback function.

In this article, we’ll look at how to pass multiple arguments into a JavaScript callback function.

How to pass multiple arguments into a JavaScript callback function?

To pass multiple arguments into a JavaScript callback function, we can use the spread operator.

For instance, we write:

const doSomething = (...args) => {
  console.log(args)
}

class SomeClass {
  constructor(callback, params) {
    this.callback = callback;
    this.params = params
  }

  method() {
    this.callback(...this.params)
  }
}

const a = ['v1text', 'v2text']
const obj = new SomeClass(doSomething, a);
obj.method()

to create the someClass class that takes a callback function and params parameters.

We set them both as values for properties of this.

And we define the method method that calls this.callback with this.params spread as arguments.

Next, we create a SomeClass instance with

const obj = new SomeClass(doSomething, a);

And then we call obj.method to call doSomething with a array.

Therefore, we see ["v1text", "v2text"] logged from doSomething.

Conclusion

To pass multiple arguments into a JavaScript callback function, we can use the spread operator.