How to use callbacks in JavaScript for event-driven apps

Today I Learned: The Power of Callbacks in JavaScript While working with event listeners, I ran into something interesting — and it made me appreciate how JavaScript handles function calls vs callbacks. Here’s the situation 👇 If I write: button.addEventListener('click', add(1, 2)); It doesn’t wait for the click. Instead, add(1, 2) gets called immediately, and the result (not the function) is passed to addEventListener. That’s why the correct approach is: button.addEventListener('click', () => add(1, 2)); Now, the function add() executes only when the event occurs — not before. 💡 Key takeaway: In JavaScript, add(1,2) executes a function, But () => add(1,2) defines a function to be executed later. This is the essence of callbacks — passing a reference to a function instead of executing it immediately. Tiny details like this make a huge difference when building interactive, event-driven apps. #JavaScript #WebDevelopment #LearningInPublic #FrontendDevelopment #Callbacks #ProgrammingTips

To view or add a comment, sign in

Explore content categories