Event Bubbling vs Event Delegation in JavaScript

🚀 JavaScript Interview Question: Event Bubbling vs Event Delegation One question I recently came across in a frontend interview was about Event Bubbling and Event Delegation in JavaScript. Let’s break it down simply 👇 🔹 Event Bubbling Event Bubbling is a mechanism where an event starts from the target element and then bubbles up to its parent elements in the DOM hierarchy. For example, if you click a button inside a div: Button → Div → Body → Document The event will trigger on the button first, then move upward to its parent elements. The event will trigger on the button first, then move upward to its parent elements. document.getElementById("parent").addEventListener("click", () => { console.log("Parent clicked"); }); document.getElementById("child").addEventListener("click", () => { console.log("Child clicked"); }); If the child is clicked, the console output will be: Child clicked Parent clicked This happens because of event bubbling. 🔹 Event Delegation Event Delegation is a technique where we attach a single event listener to a parent element instead of multiple child elements. It works because of event bubbling. Example: document.getElementById("list").addEventListener("click", (event) => { if (event.target.tagName === "LI") { console.log("List item clicked:", event.target.textContent); } }); Instead of adding listeners to every <li>, we attach one listener to the parent <ul>. 🔹 Why Event Delegation is Powerful ✅ Improves performance ✅ Reduces memory usage ✅ Works with dynamically added elements ✅ Cleaner and scalable code 💡 Interview Tip: If an interviewer asks about Event Delegation, always mention that it works because of Event Bubbling. 💬 Have you ever used event delegation in large React or JavaScript applications for performance optimization? #javascript #frontend #reactjs #webdevelopment #interviewpreparation #coding

To view or add a comment, sign in

Explore content categories