I’m trying to pass a function as a parameter in JavaScript, like this:
addContact(entityId, refreshContactList());
But the issue is that refreshContactList()
gets executed right away, instead of being passed as a function reference to be called later inside addContact.
I know using eval()
is discouraged for security reasons, so I want to avoid that. What’s the correct way to pass a function reference as a parameter in JavaScript without triggering it immediately?
Hey! The problem is that you’re calling the function when you do refreshContactList()
what you want instead is to pass the function itself:
addContact(entityId, refreshContactList);
Then inside addContact, you can choose when to run it:
function addContact(id, callback) {
// do something with id
if (typeof callback === "function") {
callback(); // only run it when needed
}
}
This makes it much more flexible, especially if you’re working in a team others can reuse addContact with different callbacks without changing its internals.
Sometimes, when you need to pass parameters to the callback, wrapping it in an arrow function works great:
addContact(entityId, () => refreshContactList(entityId));
This way, you’re still passing a function but one that’s ready to call something specific later. It helps when you’re collaborating with others and want the logic to stay modular and customizable for different contexts.
If this comes up often in your codebase, especially with team members jumping in and out, setting a clear callback structure makes your code more predictable:
function addContact(id, onComplete) {
// do something...
if (onComplete && typeof onComplete === 'function') {
onComplete();
}
}
Then everyone can just pass any function they want even from other modules without worrying about execution timing. It’s a simple pattern, but it goes a long way in collaborative setups.