How to pass parameters to callback functions in Javascript?

In many situations we need to pass parameters to a callback function, so how to do it and which is the best way to achieve it.

For example we are going to add an event click listener for a button, when we click the button, callback function will fire.

document.getElementById('button').addEventListener('click', callback);  
function callback() {  
    console.log('Have a good day!');
}

As usual we cannot pass any argument for the callback function, but some special case we need. I've tried:

var name  = 'John';  
document.getElementById('button').addEventListener('click', callback(name));  
function callback(name) {  
    console.log('Have a good day!' + name);
}

but the code above has never worked.

After researching I've found there are two approaches to help we achieve it.

1. Using Closure

var name  = 'John';  
document.getElementById('button').addEventListener('click', callback(name));

function callback(name) {  
    return function() {
        console.log('Have a good day!' + name);
    }    
}

What is Closure?

Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created. Check MDN Documentation to learn more.
So this way the argument name is in scope of the callback function when it is called.

2. Using bind()

We also have an alternative way to do it is using bind method:

See the Pen How to pass parameters to callback functions in javascript? by Nguyen Tran (@nguyentk90) on CodePen.

Both methods all are able to achieve what we to do but there are very difference in performance between them, you can check out here to find out more.

Have fun!

Nguyen Tran

I'm Nguyen, a full stack web passion for frontend and love Angular.

Subscribe to Nguyen Tran

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!