Welcome to Day 9!
Today we’re diving deep into what makes JavaScript interactive and asynchronous. You’ll learn how events work, what makes JavaScript single-threaded yet powerful, and how to handle async operations using Promises and async/await.
🖱️ JavaScript Events
An event is a user or browser action, such as clicking a button, scrolling, typing, or loading the page. JavaScript can "listen" for these events and run code when they happen.
🎯addEventListener()
– Listening for Events
Use this method to attach functions to elements:
const btn = document.querySelector(".click-me");
btn.addEventListener("click", function () {
console.log("Button was clicked!");
});
🖱️ Common Mouse Events
- click – when a user clicks
- dblclick – double-click
- mouseover – hover
- mouseout – mouse leaves
⌨️ Keyboard Events
document.addEventListener("keydown", function (e) {
console.log("Key pressed:", e.key);
});
🌊 Event Bubbling
Events bubble up from the element to its parent elements in the DOM tree.
// Bubbling example:
child.addEventListener("click", function (e) {
e.stopPropagation(); // Prevents bubbling to parent
});
📦 Event Delegation
Instead of adding listeners to multiple child elements, attach one to the parent and check e.target.
document.querySelector("ul").addEventListener("click", function (e) {
if (e.target.tagName === "LI") {
console.log("Item:", e.target.textContent);
}
});
🧠 The Event Loop & Single-Threaded JavaScript
JavaScript is single-threaded, meaning it runs one operation at a time. So how does it handle things like timers, API calls, or animations without freezing the browser?
🔁 The Event Loop
Here’s how it works:
- JavaScript runs code in the call stack.
- Long-running tasks (like setTimeout, fetch) are handled by the browser/web APIs.
- Once done, those tasks go into a callback queue.
- The event loop checks if the stack is clear and pushes queued tasks into it.
- This is how JavaScript handles asynchronous code even though it's single-threaded.
🌟 Promises – Managing Asynchronous Tasks
A Promise is an object that represents a value that may be available now, later, or never.
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received!");
}, 1000);
});
fetchData.then((data) => console.log(data));
⚡ async/await – Cleaner Way to Handle Promises
async function getData() {
try {
const response = await fetchData;
console.log(response);
} catch (error) {
console.error(error);
}
}
- async makes a function return a Promise
- await waits for the promise to resolve
✅ Mini Task: Simple Counter Using Click Events
💻 HTML:
<div>
<button id="decrease">−</button>
<span id="count">0</span>
<button id="increase">+</button>
</div>
💻 JavaScript:
const count = document.getElementById("count");
const increase = document.getElementById("increase");
const decrease = document.getElementById("decrease");
let value = 0;
increase.addEventListener("click", () => {
value++;
count.textContent = value;
});
decrease.addEventListener("click", () => {
value--;
count.textContent = value;
});
❓ Interview Questions (Day 9 Topics)
- How does addEventListener() work?
- What is the event loop in JavaScript?
- How does JavaScript handle async tasks if it's single-threaded?
- What’s the difference between Promise.then() and async/await?
- What is event delegation, and why is it useful?
🏁 Day 9 Wrap-Up
☕ If you liked this content, you can support me by buying a coffee:
Let me know when you're ready for Day 10, and I’ll wrap up the series for you in style! 💛
Top comments (0)