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)