Skip to main content

Parameters in a callback

1. By calling the callback with arguments inside a function

You pass the callback itself, and the calling function passes it the data it needs.

javascript
function fetchData(callback) { const data = 'Data from the server'; callback(data); // pass a parameter into the callback } function showData(info) { console.log('Received:', info); } fetchData(showData);

Output:

javascript
Received: Data from the server

2. Through a closure (when you need to "bake in" arguments in advance)

javascript
function processUser(action) { const user = { name: 'Tim' }; action(user); } processUser(user => console.log(`Hello, ${user.name}!`));

or:

javascript
function doLater(callback) { setTimeout(callback, 1000); } doLater(() => console.log('In a second!'));

Summary: Parameters are passed into a callback the same way as into any function - you just need to call the callback with the needed arguments inside another function.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.