🌟 Week 4 Day 8 Challenge: Ultimate Signup Form
👋 Hey Campers, hope you’re doing great! Today’s challenge is a big one 🎉. You’re going to build a Signup Form with validations + styling so it looks and feels like a real app.
✅ What to Do
Build a form with these fields:
✅Username
➤Cannot be empty.
➤At least 3 characters long.
➤No spaces allowed.
✅Email
➤Must have "@" and ".".
➤Show error if invalid.
✅Password & Confirm Password
➤Password must be at least 6 characters.
➤Confirm password must match.
✅Age
➤Must be 18 or older.
✅Phone Number
➤Must be exactly 10 digits.
✅Message / Bio
➤Optional, but if filled → at least 10 characters.
👉 Show error messages under each field.
👉 If everything is valid → display a big “Signup Successful!”.
🎨 Don’t Forget CSS!
Make it look nice:
➤Add some colors (green for success, red for errors).
➤Use margins and padding to space out inputs.
➤Add a hover effect to the submit button.
➤Maybe even round the corners with border-radius.
💡 Hints
➤Use .value.trim() to ignore empty spaces.
➤Use includes("@") and includes(".") for email checks.
➤Compare passwords with ===.
➤Use Number(age) for numeric checks.
➤Add/remove CSS classes like "error" or "success" to style feedback.
📢 Campers:
“This one is like building a real signup page 🌍. Make it functional and stylish. Share your creations, invite others to join the journey, and as always — stay well, stay curious, and stay coding ✌️.
👋 Hey Campers, hope you’re doing great! Today’s challenge is a big one 🎉. You’re going to build a Signup Form with validations + styling so it looks and feels like a real app.
✅ What to Do
Build a form with these fields:
✅Username
➤Cannot be empty.
➤At least 3 characters long.
➤No spaces allowed.
➤Must have "@" and ".".
➤Show error if invalid.
✅Password & Confirm Password
➤Password must be at least 6 characters.
➤Confirm password must match.
✅Age
➤Must be 18 or older.
✅Phone Number
➤Must be exactly 10 digits.
✅Message / Bio
➤Optional, but if filled → at least 10 characters.
👉 Show error messages under each field.
👉 If everything is valid → display a big “Signup Successful!”.
🎨 Don’t Forget CSS!
Make it look nice:
➤Add some colors (green for success, red for errors).
➤Use margins and padding to space out inputs.
➤Add a hover effect to the submit button.
➤Maybe even round the corners with border-radius.
💡 Hints
➤Use .value.trim() to ignore empty spaces.
➤Use includes("@") and includes(".") for email checks.
➤Compare passwords with ===.
➤Use Number(age) for numeric checks.
➤Add/remove CSS classes like "error" or "success" to style feedback.
📢 Campers:
“This one is like building a real signup page 🌍. Make it functional and stylish. Share your creations, invite others to join the journey, and as always — stay well, stay curious, and stay coding ✌️.
Want to study C++ or Python? My friend’s channel on YouTube uses great examples to make things easy to understand—take a look and subscribe.
https://youtube.com/@twohmschool?si=FuOAaJnKzW_WXtvZ
https://youtube.com/@twohmschool?si=FuOAaJnKzW_WXtvZ
YouTube
Two HM School
Hello 👋, everyone this is 2HM School, here we will post many educational videos , Please, subscribe, share and like our video totaly free and the only way to help us.THANK YOU ALL FOR SUPPORTING US!!!
🌟 Week 4 Day 9 — DOM Traverse, Sort & Shuffle, Date, Currency, Console Time, Destructuring
Hello Campers 👋,
First, big apology for the 3-day silence 🙏. Sometimes life gets busy. Teaching is about consistency, and I’ll keep showing up with you. Today we’ll break these topics into tiny bites with real-world meaning.
1️⃣ DOM Traversal (Walking around your HTML family tree)
Think of your HTML as a family tree:
➤Parent = the container
➤Children = elements inside it
➤Siblings = brothers/sisters (elements at the same level)
Example HTML:
JS Traversal:
👉 This is how we move around the DOM when we need not just one element but relationships.
2️⃣ Sorting Arrays
Sorting means arranging data in order (alphabetical, numeric, etc.).
Example: sorting numbers
👉 Always pass a compare function when sorting numbers.
3️⃣ Destructuring (Unpacking values quickly)
This is like saying:
“Instead of carrying a whole bag, let me just pull out the items I need.”
Arrays:
Objects:
👉 We’ll now use this in shuffling to make swaps shorter.
4️⃣ Shuffle Arrays (Randomize order)
Imagine shuffling cards in a game. We can randomize an array using the Fisher-Yates method.
👉 Thanks to destructuring, swapping values looks neat: [a, b] = [b, a];
5️⃣ Dates (Working with real-world time)
The Date object lets us work with today’s time.
👉 Note: months start at 0.
6️⃣ Currency Formatting
When showing money, we need proper formatting.
Hello Campers 👋,
First, big apology for the 3-day silence 🙏. Sometimes life gets busy. Teaching is about consistency, and I’ll keep showing up with you. Today we’ll break these topics into tiny bites with real-world meaning.
1️⃣ DOM Traversal (Walking around your HTML family tree)
Think of your HTML as a family tree:
➤Parent = the container
➤Children = elements inside it
➤Siblings = brothers/sisters (elements at the same level)
Example HTML:
<div id="family">
<p>Child 1</p>
<p>Child 2</p>
<p>Child 3</p>
</div> JS Traversal:
const parent = document.getElementById("family"); // Children (all kids) console.log(parent.children); // HTMLCollection
// ➤First & Last Child
console.log(parent.firstElementChild.textContent); // "Child 1" console.log(parent.lastElementChild.textContent); // "Child 3"
// ➤Parent of Child 2
let child2 = parent.children[1]; console.log(child2.parentElement.id); // "family"
//➤ Siblings
console.log(child2.previousElementSibling.textContent); // "Child 1"
console.log(child2.nextElementSibling.textContent); // "Child 3" 👉 This is how we move around the DOM when we need not just one element but relationships.
2️⃣ Sorting Arrays
Sorting means arranging data in order (alphabetical, numeric, etc.).
Example: sorting numbers
let scores = [40, 100, 1, 5, 25, 10];
// Wrong (default = alphabetical!) console.log(scores.sort()); // [1, 10, 100, 25, 40, 5]
// Correct numeric sort
scores.sort((a, b) => a - b);
console.log(scores); // [1, 5, 10, 25, 40, 100]
// Descending
scores.sort((a, b) => b - a);
console.log(scores); // [100, 40, 25, 10, 5, 1] 👉 Always pass a compare function when sorting numbers.
3️⃣ Destructuring (Unpacking values quickly)
This is like saying:
“Instead of carrying a whole bag, let me just pull out the items I need.”
Arrays:
let colors = ["red", "green", "blue"];
// Without destructuring:
let first = colors[0];
let second = colors[1];
// With destructuring:
let [c1, c2, c3] = colors;
console.log(c1); // red
console.log(c2); // green
console.log(c3); // blue Objects:
let student = { name: "Amina", age: 20, city: "Addis" };
// Without destructuring:
let n = student.name;
let c = student.city;
// With destructuring:
let { name, city } = student;
console.log(name); // Amina
console.log(city); // Addis
👉 We’ll now use this in shuffling to make swaps shorter.
4️⃣ Shuffle Arrays (Randomize order)
Imagine shuffling cards in a game. We can randomize an array using the Fisher-Yates method.
let students = ["Aman", "Lily", "Sara", "Kebede", "Muna"];
for (let i = students.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
// Swap students[i] with students[j]
[students[i], students[j]] = [students[j], students[i]]; // destructuring swap }
console.log(students); 👉 Thanks to destructuring, swapping values looks neat: [a, b] = [b, a];
5️⃣ Dates (Working with real-world time)
The Date object lets us work with today’s time.
let now = new Date();
console.log(now); // full date & time
console.log(now.getFullYear()); // year
console.log(now.getMonth()); // 0-11 (0 = January)
console.log(now.getDate()); // day of month
console.log(now.getDay()); // 0-6 (0 = Sunday)
console.log(now.getHours()); // hour
console.log(now.toDateString()); // "Tue Aug 26 2025"
console.log(now.toLocaleString()); // local format 👉 Note: months start at 0.
6️⃣ Currency Formatting
When showing money, we need proper formatting.
let price = 12345.678;
// USD
console.log( new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(price) ); // $12,345.68
// Ethiopian Birr
console.log( new Intl.NumberFormat("am-ET", { style: "currency", currency: "ETB" }).format(price) ); // Br 12,345.68👉 Intl.NumberFormat automatically localizes numbers & symbols.
7️⃣ Measuring Code Speed with console.time
We can measure how long a block of code takes to run.
👉 Useful when comparing different ways of solving a problem.
🎯 Wrap Up
Today we learned:
✔ How to move around HTML elements (DOM traversal)
✔ Sorting & shuffling arrays (with destructuring explained first!)
✔ Dates and how to format them
✔ Currency formatting for real apps
✔ Measuring performance with console.time
✔ Cleaner code with destructuring
Each of these may look small, but together they give you real-world tools you’ll use in projects like calculators, dashboards, games, and even ecommerce apps.
7️⃣ Measuring Code Speed with console.time
We can measure how long a block of code takes to run.
console.time("loop test");
let sum = 0;
for (let i = 0; i < 1_000_000; i++) {
sum += i; }
console.timeEnd("loop test");
// e.g. loop test: 12ms 👉 Useful when comparing different ways of solving a problem.
🎯 Wrap Up
Today we learned:
✔ How to move around HTML elements (DOM traversal)
✔ Sorting & shuffling arrays (with destructuring explained first!)
✔ Dates and how to format them
✔ Currency formatting for real apps
✔ Measuring performance with console.time
✔ Cleaner code with destructuring
Each of these may look small, but together they give you real-world tools you’ll use in projects like calculators, dashboards, games, and even ecommerce apps.
Assignment :
➤Dom traverse
https://youtu.be/RKXIMnSwUcg?si=FUKj1D4b7pC7XpFq
➤currency
https://youtu.be/HOMu48bTzz8?si=rERc7uTzUX89twhi
➤console.time
https://youtu.be/9amAW_qXv84?si=SA02eHAMPjKnn0Xf
➤date objects
https://youtu.be/LwYwz67l1lA?si=BRjHz1NMzeaxuyvH
➤shuffle
https://youtu.be/FGAUekwri1Q?si=HOUJ2olxK-PiBQNO
➤sorting
https://youtu.be/CTHhlx25X-U?si=nW90hcx3kTpSKiuo
➤destructuring
https://youtu.be/UHZcJyVXtLo?si=zpy9s31wdychlRm7
➤Dom traverse
https://youtu.be/RKXIMnSwUcg?si=FUKj1D4b7pC7XpFq
➤currency
https://youtu.be/HOMu48bTzz8?si=rERc7uTzUX89twhi
➤console.time
https://youtu.be/9amAW_qXv84?si=SA02eHAMPjKnn0Xf
➤date objects
https://youtu.be/LwYwz67l1lA?si=BRjHz1NMzeaxuyvH
➤shuffle
https://youtu.be/FGAUekwri1Q?si=HOUJ2olxK-PiBQNO
➤sorting
https://youtu.be/CTHhlx25X-U?si=nW90hcx3kTpSKiuo
➤destructuring
https://youtu.be/UHZcJyVXtLo?si=zpy9s31wdychlRm7
YouTube
Learn DOM Navigation in 15 minutes! 🧭
#JavaScript #tutorial #course
00:00:00 introduction
00:01:25 .firstElementChild
00:04:33 .lastElementChild
00:07:02 .nextElementSibling
00:10:03 .previousElementSibling
00:11:48 .parentElement
00:12:55 .children
00:15:04 conclusion
// DOM Navigation = The…
00:00:00 introduction
00:01:25 .firstElementChild
00:04:33 .lastElementChild
00:07:02 .nextElementSibling
00:10:03 .previousElementSibling
00:11:48 .parentElement
00:12:55 .children
00:15:04 conclusion
// DOM Navigation = The…
🌟 Project 1: Calculator & Digital Clock
Hello Campers 👋
I know we still haven't finished JavaScript , but it's time to use what we have learned so far for two real mini-apps. Using google is allowed, but make sure you understand every line of code.
1) 🧮 Calculator (Basic → Plus)
✅ What to build
A clean on-page calculator with:
➤Display screen
➤Buttons: 0–9, + - × ÷, . (decimal), =, C (clear), ← (backspace)
🧩 Core features
➤Click buttons to show numbers/operators on the display
➤= evaluates the expression and shows the result
➤C clears everything, ← removes last character
➤Prevent invalid inputs (e.g., two operators in a row)
🛠️ Suggested structure
✅HTML
▶️<div class="calc"> with a <input id="display" readonly>
▶️A grid of <button>s for digits/operators
✅CSS (ideas)
▶️Use CSS Grid for the buttons
▶️:hover and :active styles for click feedback
▶️Bigger font for display, subtle shadow for the calculator body
✅JS (flow)
▶️Grab all buttons and the display (document.getElementById, querySelectorAll)
▶️On button click, update display.value
▶️On =, safely evaluate (don’t use raw eval in real apps; for now you can map ×→*, ÷→/ and evaluate using Function or a simple parser)
▶️On C, set display.value = ''
▶️On ←, remove last char:
▶️display.value = display.value.slice(0, -1)
↪️Edge cases: avoid .. twice, avoid ++, --, **, //, and starting with an operator (except minus if you want negative numbers)
💡 Hints
➥Keep allowed chars list: digits 0–9, ., + - * /
➥Replace visual operators before evaluation: ➥input.replaceAll('×','*').replaceAll('÷','/')
➥Disable multiple operators in a row by checking the last character before appending
➥Optional: add keyboard support with keydown events
2) ⏰ Digital Clock (Live Time + Options)
✅ What to build
A live clock that updates every second:
Hours:Minutes:Seconds
AM/PM (12-hour) and 24-hour toggle
Day and date display
🧩 Core features
➤Show current time (HH:MM:SS)
➤Update every 1000 ms with setInterval
Format leading zeros (e.g., 09:05:03)
➤Show day name and full date
🛠️ Suggested structure
HTML
<div class="clock">
<div id="time"></div>
<div id="date"></div>
<button id="toggleFormat">Switch 12/24h</button>
CSS (ideas)
➤Big monospace font for time
➤Subtle gradient background
➤Center with Flexbox, add soft glow text-shadow
JS (flow)
➤Keep a state: let is24 = false;
➤function updateClock() {
const now = new Date()
Get hours/minutes/seconds
➤If 12-hour: hour = hour % 12 || 12 and add AM/PM
➤Format with a helper: pad(n) => n.toString().padStart(2,'0')
➤Build date string (e.g., Sunday, 17 September 2025)
Put into #time and #date
}
➤setInterval(updateClock, 1000); updateClock();
On toggle button click, flip is24 and re-render
💡 Hints
Arrays help format names:
➥const days = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
➥const months = ["Jan","Feb",...,"Dec"];
➥Use textContent to update DOM efficiently
➥Use a single interval; don’t create multiple intervals on each click
📣 Final Notes
✅Keep your code clean: separate HTML structure, CSS styling, and JS behavior
✅Test edge cases (empty display on =, multiple operators, midnight formats, etc.)
Share your finished projects in the group, invite your friends, and as always—
stay well, stay curious, and stay coding ✌️
Hello Campers 👋
I know we still haven't finished JavaScript , but it's time to use what we have learned so far for two real mini-apps. Using google is allowed, but make sure you understand every line of code.
1) 🧮 Calculator (Basic → Plus)
✅ What to build
A clean on-page calculator with:
➤Display screen
➤Buttons: 0–9, + - × ÷, . (decimal), =, C (clear), ← (backspace)
🧩 Core features
➤Click buttons to show numbers/operators on the display
➤= evaluates the expression and shows the result
➤C clears everything, ← removes last character
➤Prevent invalid inputs (e.g., two operators in a row)
🛠️ Suggested structure
✅HTML
▶️<div class="calc"> with a <input id="display" readonly>
▶️A grid of <button>s for digits/operators
✅CSS (ideas)
▶️Use CSS Grid for the buttons
▶️:hover and :active styles for click feedback
▶️Bigger font for display, subtle shadow for the calculator body
✅JS (flow)
▶️Grab all buttons and the display (document.getElementById, querySelectorAll)
▶️On button click, update display.value
▶️On =, safely evaluate (don’t use raw eval in real apps; for now you can map ×→*, ÷→/ and evaluate using Function or a simple parser)
▶️On C, set display.value = ''
▶️On ←, remove last char:
▶️display.value = display.value.slice(0, -1)
↪️Edge cases: avoid .. twice, avoid ++, --, **, //, and starting with an operator (except minus if you want negative numbers)
💡 Hints
➥Keep allowed chars list: digits 0–9, ., + - * /
➥Replace visual operators before evaluation: ➥input.replaceAll('×','*').replaceAll('÷','/')
➥Disable multiple operators in a row by checking the last character before appending
➥Optional: add keyboard support with keydown events
2) ⏰ Digital Clock (Live Time + Options)
✅ What to build
A live clock that updates every second:
Hours:Minutes:Seconds
AM/PM (12-hour) and 24-hour toggle
Day and date display
🧩 Core features
➤Show current time (HH:MM:SS)
➤Update every 1000 ms with setInterval
Format leading zeros (e.g., 09:05:03)
➤Show day name and full date
🛠️ Suggested structure
HTML
<div class="clock">
<div id="time"></div>
<div id="date"></div>
<button id="toggleFormat">Switch 12/24h</button>
CSS (ideas)
➤Big monospace font for time
➤Subtle gradient background
➤Center with Flexbox, add soft glow text-shadow
JS (flow)
➤Keep a state: let is24 = false;
➤function updateClock() {
const now = new Date()
Get hours/minutes/seconds
➤If 12-hour: hour = hour % 12 || 12 and add AM/PM
➤Format with a helper: pad(n) => n.toString().padStart(2,'0')
➤Build date string (e.g., Sunday, 17 September 2025)
Put into #time and #date
}
➤setInterval(updateClock, 1000); updateClock();
On toggle button click, flip is24 and re-render
💡 Hints
Arrays help format names:
➥const days = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
➥const months = ["Jan","Feb",...,"Dec"];
➥Use textContent to update DOM efficiently
➥Use a single interval; don’t create multiple intervals on each click
📣 Final Notes
✅Keep your code clean: separate HTML structure, CSS styling, and JS behavior
✅Test edge cases (empty display on =, multiple operators, midnight formats, etc.)
Share your finished projects in the group, invite your friends, and as always—
stay well, stay curious, and stay coding ✌️
🎉1
🌞 Week 5 Day 1 — Introduction to Asynchronous JavaScript
👋 Hello Campers!
Welcome to Week 5 of our Fullstack Summer Camp! We’ve been doing an amazing job so far — from variables and functions, all the way to DOM and OOP. Today, we are stepping into one of the most important (and a bit tricky) parts of JavaScript: Asynchronous Programming.
Don’t worry — we’ll take it step by step, with simple words, good analogies, and examples.
🕐 1. First, What Does "Asynchronous" Mean?
Synchronous = things happen one after the other.
Example: You stand in line to buy injera 🥙. Each person must finish buying before the next can order.
Asynchronous = things can happen while waiting.
Example: You order coffee ☕ at a café. The waiter tells you to sit, and while the coffee is being prepared, you can check your phone, talk to a friend, or do homework. You don’t need to stand stuck until it’s ready.
👉 That’s what JavaScript does: it allows some tasks to happen in the background (like waiting for data, downloading files, or timers) while the rest of the code keeps running.
🧵 2. Why Do We Need Async in JavaScript?
JavaScript is single-threaded — it can only do one thing at a time. If we write blocking code (like waiting 5 seconds), the whole page will freeze 😳.
Imagine:
You open a website.
The website tries to download a 5MB image.
If JavaScript was synchronous only, the entire page would stop until the image finished downloading. No scrolling, no clicking, nothing.
Asynchronous programming fixes this → it lets JS say:
👉 “Okay, I’ll start downloading this, but meanwhile, let me keep running the rest of the code. I’ll come back when the download is ready.”
🌀 3. The Event Loop — JavaScript’s Coffee Shop ☕
Here’s the magic of how async works:
➤Call Stack → where JavaScript runs your main code (line by line).
➤Web APIs / Background tasks → where timers, fetch requests, etc., wait.
➤Callback Queue → when those tasks are finished, they move here.
➤Event Loop → a helper that checks: “Is the stack empty? If yes, I’ll take a task from the queue and run it.”
👉 Analogy:
Think of a coffee shop:
➤The cashier = Call Stack (takes orders).
➤The barista = Web API (prepares coffee in the back).
➤The pick-up counter = Callback Queue (finished coffees waiting).
➤The waiter = Event Loop (delivers coffee when the cashier is free).
So, JS can keep “taking orders” while some work happens in the background.
💻 4. Examples of Synchronous vs Asynchronous
Example 1: Synchronous
Output (always in order):
Everything waits for the previous step.
Example 2: Asynchronous with setTimeout
Output:
👉 Notice: “Talk with friend” runs before coffee is ready. That’s async!
🔧 5. Common Asynchronous Functions in JS
➤setTimeout() → run code after some delay.
➤setInterval() → run code repeatedly after a time gap.
➤fetch() → get data from a server (we’ll learn in detail later).
➤Event listeners → e.g., when user clicks, the function is called later.
All these don’t block the code — they run in the background and “come back” when ready.
🌍 6. Real-World Examples
➤When you type in Google search → results load without reloading the whole page (async API calls).
➤When you scroll Instagram → new posts load in the background.
➤When you press play on YouTube → video streams while comments load separately.
📝 Key Takeaways
➤JavaScript is single-threaded (one main line of execution).
➤To avoid blocking, it uses asynchronous programming.
➤Async tasks (timers, requests, events) go to the Web APIs → then return later via the Event Loop.
➤Async = smoother, faster, more user-friendly apps.
👋 Hello Campers!
Welcome to Week 5 of our Fullstack Summer Camp! We’ve been doing an amazing job so far — from variables and functions, all the way to DOM and OOP. Today, we are stepping into one of the most important (and a bit tricky) parts of JavaScript: Asynchronous Programming.
Don’t worry — we’ll take it step by step, with simple words, good analogies, and examples.
🕐 1. First, What Does "Asynchronous" Mean?
Synchronous = things happen one after the other.
Example: You stand in line to buy injera 🥙. Each person must finish buying before the next can order.
Asynchronous = things can happen while waiting.
Example: You order coffee ☕ at a café. The waiter tells you to sit, and while the coffee is being prepared, you can check your phone, talk to a friend, or do homework. You don’t need to stand stuck until it’s ready.
👉 That’s what JavaScript does: it allows some tasks to happen in the background (like waiting for data, downloading files, or timers) while the rest of the code keeps running.
🧵 2. Why Do We Need Async in JavaScript?
JavaScript is single-threaded — it can only do one thing at a time. If we write blocking code (like waiting 5 seconds), the whole page will freeze 😳.
Imagine:
You open a website.
The website tries to download a 5MB image.
If JavaScript was synchronous only, the entire page would stop until the image finished downloading. No scrolling, no clicking, nothing.
Asynchronous programming fixes this → it lets JS say:
👉 “Okay, I’ll start downloading this, but meanwhile, let me keep running the rest of the code. I’ll come back when the download is ready.”
🌀 3. The Event Loop — JavaScript’s Coffee Shop ☕
Here’s the magic of how async works:
➤Call Stack → where JavaScript runs your main code (line by line).
➤Web APIs / Background tasks → where timers, fetch requests, etc., wait.
➤Callback Queue → when those tasks are finished, they move here.
➤Event Loop → a helper that checks: “Is the stack empty? If yes, I’ll take a task from the queue and run it.”
👉 Analogy:
Think of a coffee shop:
➤The cashier = Call Stack (takes orders).
➤The barista = Web API (prepares coffee in the back).
➤The pick-up counter = Callback Queue (finished coffees waiting).
➤The waiter = Event Loop (delivers coffee when the cashier is free).
So, JS can keep “taking orders” while some work happens in the background.
💻 4. Examples of Synchronous vs Asynchronous
Example 1: Synchronous
console.log("1. Order injera");
console.log("2. Wait until injera is ready");
console.log("3. Eat injera"); Output (always in order):
1. Order injera
2. Wait until injera is ready
3. Eat injera Everything waits for the previous step.
Example 2: Asynchronous with setTimeout
console.log("1. Order coffee");
setTimeout(() => { console.log("2. Coffee is ready!"); }, 2000);
console.log("3. Talk with friend"); Output:
1. Order coffee
3. Talk with friend
2. Coffee is ready! 👉 Notice: “Talk with friend” runs before coffee is ready. That’s async!
🔧 5. Common Asynchronous Functions in JS
➤setTimeout() → run code after some delay.
➤setInterval() → run code repeatedly after a time gap.
➤fetch() → get data from a server (we’ll learn in detail later).
➤Event listeners → e.g., when user clicks, the function is called later.
All these don’t block the code — they run in the background and “come back” when ready.
🌍 6. Real-World Examples
➤When you type in Google search → results load without reloading the whole page (async API calls).
➤When you scroll Instagram → new posts load in the background.
➤When you press play on YouTube → video streams while comments load separately.
📝 Key Takeaways
➤JavaScript is single-threaded (one main line of execution).
➤To avoid blocking, it uses asynchronous programming.
➤Async tasks (timers, requests, events) go to the Web APIs → then return later via the Event Loop.
➤Async = smoother, faster, more user-friendly apps.
📖 Week 5 Day 1 — Asynchronous JS Reading Challenge
Goal: Make sure you really understand what async is, why it exists, and how JS handles tasks in the background.
🔹 Part 1: Quick Questions
Answer these without looking back at the lesson first — test your memory and understanding.Explain in your own words:
1.What’s the difference between synchronous and asynchronous code?
2.Imagine you’re in a café:
➥Which part of the coffee process is like the Call Stack?
➥Which part is like the Web API / background task?
➥Which part is like the Callback Queue?
➥Who is the Event Loop in this analogy?
3.Why would a JavaScript web page freeze if we didn’t use asynchronous code?
4.List 2 examples of asynchronous functions in JS and explain what they do.
🔹 Part 2: True or False
1,setTimeout blocks the rest of your code until it finishes.
2,JavaScript can do multiple things at the exact same time on its main thread.
3,Asynchronous code helps make apps faster and smoother.
4,The Event Loop checks if the Call Stack is empty before moving tasks from the Callback Queue.
🔹 Part 3: Scenario Thinking
Read the scenarios and explain what will happen first:
1.You order coffee ☕ (takes 3 minutes), start talking to a friend, and the waiter brings your coffee when ready.
Which happens first: talking to a friend or getting coffee?
2.You request data from a server using fetch(). While waiting, you click a button that opens a popup.
Will the popup wait for the data to finish downloading, or appear immediately?
3.You use setTimeout for 5 seconds to show a message, but in the meantime, you print “Hello” to the console.
What gets logged first: “Hello” or the 5-second message?
🔹 Part 4: Reflection
Write 2–3 sentences about why you think asynchronous programming is important for real websites and apps. Use examples from Google, Instagram, or YouTube.
Don’t forget to
💥💥 share your solutions,
💥💥invite your friends,
and as always…
💥💥✌️✌️stay well, stay curious, and stay coding ✌️
Goal: Make sure you really understand what async is, why it exists, and how JS handles tasks in the background.
🔹 Part 1: Quick Questions
Answer these without looking back at the lesson first — test your memory and understanding.Explain in your own words:
1.What’s the difference between synchronous and asynchronous code?
2.Imagine you’re in a café:
➥Which part of the coffee process is like the Call Stack?
➥Which part is like the Web API / background task?
➥Which part is like the Callback Queue?
➥Who is the Event Loop in this analogy?
3.Why would a JavaScript web page freeze if we didn’t use asynchronous code?
4.List 2 examples of asynchronous functions in JS and explain what they do.
🔹 Part 2: True or False
1,setTimeout blocks the rest of your code until it finishes.
2,JavaScript can do multiple things at the exact same time on its main thread.
3,Asynchronous code helps make apps faster and smoother.
4,The Event Loop checks if the Call Stack is empty before moving tasks from the Callback Queue.
🔹 Part 3: Scenario Thinking
Read the scenarios and explain what will happen first:
1.You order coffee ☕ (takes 3 minutes), start talking to a friend, and the waiter brings your coffee when ready.
Which happens first: talking to a friend or getting coffee?
2.You request data from a server using fetch(). While waiting, you click a button that opens a popup.
Will the popup wait for the data to finish downloading, or appear immediately?
3.You use setTimeout for 5 seconds to show a message, but in the meantime, you print “Hello” to the console.
What gets logged first: “Hello” or the 5-second message?
🔹 Part 4: Reflection
Write 2–3 sentences about why you think asynchronous programming is important for real websites and apps. Use examples from Google, Instagram, or YouTube.
Don’t forget to
💥💥 share your solutions,
💥💥invite your friends,
and as always…
💥💥✌️✌️stay well, stay curious, and stay coding ✌️
🌞 Week 5 Day 2 — Callbacks in Async (setTimeout, setInterval)
👋 Hello Campers!
Ready for day 2 of async JavaScript? Yesterday we built the mindset (single-threaded JS, event loop). Today we’ll use two core async tools—setTimeout and setInterval—and learn what a callback really is, why “callback hell” happens, and how to avoid it. We’ll end with small, real-world demos (delayed messages + simple timers). Let’s go. 🚀
1) What is a callback?
A callback is just a function you pass to another function so it can be called later (when something is ready).
✅Sync callback (runs immediately):
✅Async callback (runs later):
Analogy: you give a café your phone number (callback). When the coffee is ready (async), they call you back.
2) setTimeout — run once after a delay
Syntax
➤callback: function to run later
➤delayMs: delay in milliseconds
➤returns a timer ID (so you can cancel)
Basic examples
Cancel a scheduled timeout
Important notes
The delay is minimum time. The callback runs as soon as the call stack is free (event loop).
Always save the timer ID if you might cancel it.
3) setInterval — run repeatedly every N ms
Syntax
Basic example
Cancel a repeating interval
Caution
Intervals can “drift” a little (not perfectly on time). For critical timing, prefer a self-scheduling timeout.
4) Real-world mini demos
A) Delayed welcome message (one-time setTimeout)
B) Simple countdown (with setInterval)
C) Stopwatch (start/stop/reset) — self-contained logic
👋 Hello Campers!
Ready for day 2 of async JavaScript? Yesterday we built the mindset (single-threaded JS, event loop). Today we’ll use two core async tools—setTimeout and setInterval—and learn what a callback really is, why “callback hell” happens, and how to avoid it. We’ll end with small, real-world demos (delayed messages + simple timers). Let’s go. 🚀
1) What is a callback?
A callback is just a function you pass to another function so it can be called later (when something is ready).
✅Sync callback (runs immediately):
[1, 2, 3].forEach(function (n) { console.log(n); // runs now, during forEach });
✅Async callback (runs later):
setTimeout(function () { console.log("Runs after 1000ms"); }, 1000);
Analogy: you give a café your phone number (callback). When the coffee is ready (async), they call you back.
2) setTimeout — run once after a delay
Syntax
const timerId = setTimeout(callback, delayMs, arg1, arg2, ...);
➤callback: function to run later
➤delayMs: delay in milliseconds
➤returns a timer ID (so you can cancel)
Basic examples
setTimeout(() => { console.log("Hello after 2 seconds"); }, 2000); // Passing data to the callback function
greet(name) { console.log(Hi, ${name}!); }
setTimeout(greet, 1500, "Muna"); // "Hi, Muna!" after 1.5s
Cancel a scheduled timeout
const id = setTimeout(() => console.log("This will never run"), 3000);
clearTimeout(id);
Important notes
The delay is minimum time. The callback runs as soon as the call stack is free (event loop).
Always save the timer ID if you might cancel it.
3) setInterval — run repeatedly every N ms
Syntax
const intervalId = setInterval(callback, intervalMs, arg1, arg2, ...);
Basic example
const id = setInterval(() => { console.log(new Date().toLocaleTimeString()); }, 1000); // Stop after 5 seconds
setTimeout(() => clearInterval(id), 5000);
Cancel a repeating interval
clearInterval(intervalId);
Caution
Intervals can “drift” a little (not perfectly on time). For critical timing, prefer a self-scheduling timeout.
4) Real-world mini demos
A) Delayed welcome message (one-time setTimeout)
<div id="msg" style="display:none; padding:8px; background:#eef;"> Welcome back! 🎉 </div>
<script>
const msg = document.getElementById("msg"); // Show after 1.5 seconds
const showId = setTimeout(() => { msg.style.display = "block"; // Hide again after 3 seconds
setTimeout(() => (msg.style.display = "none"), 3000); }, 1500);
</script>
B) Simple countdown (with setInterval)
let seconds = 5;
const id = setInterval(() => {
console.log(seconds);
if (seconds === 0) { console.log("Go! 🚀");
clearInterval(id); }
seconds--; }, 1000);
C) Stopwatch (start/stop/reset) — self-contained logic
<div>
<div id="time" style="font: 24px monospace;">00:00.0</div>
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button>
</div>
<script>
const timeEl = document.getElementById("time");
const startBtn = document.getElementById("start");
const stopBtn = document.getElementById("stop");
const resetBtn = document.getElementById("reset");
let startAt = null; // timestamp when started
let tickId = null; // interval ID
function format(ms) { const total = Math.floor(ms / 100);
const mm = String(Math.floor(total / 600)).padStart(2, "0"); // minutes
const ss = String(Math.floor((total % 600) / 10)).padStart(2, "0"); // seconds
const t = total % 10; // tenths
return ${mm}:${ss}.${t}; }
function update() {
const elapsed = Date.now() - startAt;
timeEl.textContent = format(elapsed); }
startBtn.onclick = () => { if (tickId) return; // already running
startAt = Date.now() - (parseFloat(timeEl.textContent.replace(/[:.]/g,'')) || 0);
tickId = setInterval(update, 100); // update every 100ms };
stopBtn.onclick = () => { clearInterval(tickId); tickId = null; };
resetBtn.onclick = () => { clearInterval(tickId); tickId = null; timeEl.textContent = "00:00.0"; };
</script>
5) Callback Hell (the “Pyramid of Doom”)
When async steps depend on each other and you keep nesting callbacks inside callbacks, your code can become hard to read, test, and maintain.
Example: three steps in order (bad nesting)
Problems:
➤Hard to read (moves to the right like a pyramid)
➤Hard to handle errors
➤Hard to reuse parts
How to reduce the pain (without Promises yet)
A) Use named functions (flatten the shape):
B) Self-scheduling pattern (recursion style):
Next lessons will fix this elegantly with Promises and async/await (much cleaner than deep nesting).
6) setInterval vs “recursive” setTimeout
setInterval(fn, 1000) tries to run every 1000ms. If fn takes long, calls can bunch up or drift.
A safer approach for consistent spacing is self-scheduling:
This avoids overlapping calls and adapts to work time.
7) Common mistakes & best practices
✅ Store timer IDs (const id = setTimeout(...);) if you might cancel them.
✅ Clean up intervals with clearInterval(id) when you’re done (avoid “zombie” timers).
✅ Keep callbacks small and named where possible (easier to debug).
⚠️ Don’t assume the exact delay; the event loop controls when callbacks actually run.
⚠️ Avoid deep nesting → prefer named functions or (soon) Promises / async-await.
8) Tiny utility helpers
➤Leading zeros (e.g., 09:05:03):
➤Debounce concept (preview) — wait until the user stops typing:
(You’ll use this a lot when we reach real search boxes and forms.)
Recap
✅Callback = a function to run later.
✅setTimeout → run once after a delay; ✅clearTimeout to cancel.
✅setInterval → run repeatedly; ✅clearInterval to stop.
✅Callback hell happens with deep nesting—fight it with named functions or the self-scheduling pattern (and soon with Promises/async-await).
✅Real-world uses: delayed messages, countdowns, clocks, stopwatches, reminders.
That’s today’s deep dive 💪. Next up: Promises—a cleaner, more powerful way to write async code (goodbye pyramid of doom).
When async steps depend on each other and you keep nesting callbacks inside callbacks, your code can become hard to read, test, and maintain.
Example: three steps in order (bad nesting)
setTimeout(() => {
console.log("Step 1");
setTimeout(() => {
console.log("Step 2");
setTimeout(() => {
console.log("Step 3"); // keep going... 😵 }, 1000);
}, 1000);
}, 1000); Problems:
➤Hard to read (moves to the right like a pyramid)
➤Hard to handle errors
➤Hard to reuse parts
How to reduce the pain (without Promises yet)
A) Use named functions (flatten the shape):
function step1() {
console.log("Step 1");
setTimeout(step2, 1000); }
function step2() {
console.log("Step 2");
setTimeout(step3, 1000); }
function step3() {
console.log("Step 3"); }
setTimeout(step1, 1000); B) Self-scheduling pattern (recursion style):
function runStep(n, max) {
if (n > max) return; console.log("Step", n);
setTimeout(() => runStep(n + 1, max), 1000); }
runStep(1, 3); Next lessons will fix this elegantly with Promises and async/await (much cleaner than deep nesting).
6) setInterval vs “recursive” setTimeout
setInterval(fn, 1000) tries to run every 1000ms. If fn takes long, calls can bunch up or drift.
A safer approach for consistent spacing is self-scheduling:
function tick() {
console.log(new Date().toLocaleTimeString());
setTimeout(tick, 1000); // schedule the next tick after this finishes }
tick(); This avoids overlapping calls and adapts to work time.
7) Common mistakes & best practices
✅ Store timer IDs (const id = setTimeout(...);) if you might cancel them.
✅ Clean up intervals with clearInterval(id) when you’re done (avoid “zombie” timers).
✅ Keep callbacks small and named where possible (easier to debug).
⚠️ Don’t assume the exact delay; the event loop controls when callbacks actually run.
⚠️ Avoid deep nesting → prefer named functions or (soon) Promises / async-await.
8) Tiny utility helpers
➤Leading zeros (e.g., 09:05:03):
const pad2 = (n) => String(n).padStart(2, "0"); ➤Debounce concept (preview) — wait until the user stops typing:
function debounce(fn, delay) {
let id;
return (...args) => {
clearTimeout(id);
id = setTimeout(() => fn(...args), delay); }; } // Usage later with input events (You’ll use this a lot when we reach real search boxes and forms.)
Recap
✅Callback = a function to run later.
✅setTimeout → run once after a delay; ✅clearTimeout to cancel.
✅setInterval → run repeatedly; ✅clearInterval to stop.
✅Callback hell happens with deep nesting—fight it with named functions or the self-scheduling pattern (and soon with Promises/async-await).
✅Real-world uses: delayed messages, countdowns, clocks, stopwatches, reminders.
That’s today’s deep dive 💪. Next up: Promises—a cleaner, more powerful way to write async code (goodbye pyramid of doom).
Assignment:
➤setTimeOut
https://youtu.be/shWr5DNVeCI?si=pjfo7hBT3QaHJJNg
➤callback hell
https://youtu.be/NOlOw03qBfw?si=-K-hbG2-TtQxQez_
➤setTimeOut
https://youtu.be/shWr5DNVeCI?si=pjfo7hBT3QaHJJNg
➤callback hell
https://youtu.be/NOlOw03qBfw?si=-K-hbG2-TtQxQez_
YouTube
Learn JavaScript setTimeout() in 6 minutes! ⏰
00:00:00 introduction
00:00:30 setTimeout w/ callback
00:01:04 setTimeout w/ anonymous functions
00:01:25 setTimeout w/ arrow funcitons
00:01:43 clearTimeout()
00:02:32 start button
00:03:51 clear button
00:05:49 conclusion
// setTimeout() = function in…
00:00:30 setTimeout w/ callback
00:01:04 setTimeout w/ anonymous functions
00:01:25 setTimeout w/ arrow funcitons
00:01:43 clearTimeout()
00:02:32 start button
00:03:51 clear button
00:05:49 conclusion
// setTimeout() = function in…
💥 Week 5 Day 2 — Async Callback Challenges
Hey Campers 👋, you did great today learning about callbacks in async tasks (like setTimeout & setInterval) and also about the infamous Callback Hell 🌀.
Now it’s time to practice! Here are 4 challenge ideas.
1. Delayed Welcome Message
👉 Write a function that shows "Welcome Camper!" after 3 seconds using setTimeout.
💡 Hint: Wrap your console.log inside a setTimeout.
2. Simple Digital Timer
👉 Build a timer that counts up from 0 seconds and displays it in the console every second. Stop it after 10 seconds.
💡 Hint: Use setInterval to keep counting, and clearInterval to stop it.
3. Countdown Launcher 🚀
👉 Create a countdown starting from 5 down to 1, then finally log "Blast off!".
💡 Hint: setInterval works well here, but make sure to stop it at the right time.
4. Sequential Messages
👉 Show these messages in order with delays:
After 1s → "Preparing..."
After 3s → "Loading..."
After 5s → "Ready!"
💡 Hint: Use multiple setTimeout calls — this will give you a taste of callback hell! 😅
👉 Don’t forget to
💥 share your solutions in the group,
💥invite a friend,
and as always —
💥stay well, stay curious, and stay coding ✌️
Hey Campers 👋, you did great today learning about callbacks in async tasks (like setTimeout & setInterval) and also about the infamous Callback Hell 🌀.
Now it’s time to practice! Here are 4 challenge ideas.
1. Delayed Welcome Message
👉 Write a function that shows "Welcome Camper!" after 3 seconds using setTimeout.
💡 Hint: Wrap your console.log inside a setTimeout.
2. Simple Digital Timer
👉 Build a timer that counts up from 0 seconds and displays it in the console every second. Stop it after 10 seconds.
💡 Hint: Use setInterval to keep counting, and clearInterval to stop it.
3. Countdown Launcher 🚀
👉 Create a countdown starting from 5 down to 1, then finally log "Blast off!".
💡 Hint: setInterval works well here, but make sure to stop it at the right time.
4. Sequential Messages
👉 Show these messages in order with delays:
After 1s → "Preparing..."
After 3s → "Loading..."
After 5s → "Ready!"
💡 Hint: Use multiple setTimeout calls — this will give you a taste of callback hell! 😅
👉 Don’t forget to
💥 share your solutions in the group,
💥invite a friend,
and as always —
💥stay well, stay curious, and stay coding ✌️
👍2
🔥 Reality Check for Beginner Coders 🔥
Listen—watching 100 YouTube tutorials won’t make you a coder.
Writing one small messy project will teach you more than all those videos combined.
Stop fooling yourself with “I’ll start after I finish this tutorial” or “I need to know everything first.”
You’ll never know everything. And you don’t need to.
💡 Build something small. A calculator. A to-do list. A digital clock.
It won’t be perfect—good. It doesn’t have to be. Coding isn’t about perfection, it’s about consistency.
Don’t make 10 big plans a day and execute none. Make 1 simple plan and show up for it every day.
Consistency beats motivation. Consistency beats talent.
And when you get stuck? Ask. Even if your question feels “dumb.” The dumb question you ask today is the breakthrough you needed yesterday.
Mistakes? You’ll make tons. That’s how you learn. Every bug you fight, every error you fix, becomes knowledge you’ll never forget.
Here’s the raw truth:
✨ No mentor, no tutorial, no friend can carry your dream. It’s you. Only you.
If you want it, you fight for it. You sit, you code, you fail, you repeat.
Because in the end—your future, your dream, your freedom—isn’t waiting on YouTube.
It’s waiting on your hands to type that first line of code.
⚡ Stop hiding. Start building. Even the smallest project is a step toward the life you want. ⚡
Listen—watching 100 YouTube tutorials won’t make you a coder.
Writing one small messy project will teach you more than all those videos combined.
Stop fooling yourself with “I’ll start after I finish this tutorial” or “I need to know everything first.”
You’ll never know everything. And you don’t need to.
💡 Build something small. A calculator. A to-do list. A digital clock.
It won’t be perfect—good. It doesn’t have to be. Coding isn’t about perfection, it’s about consistency.
Don’t make 10 big plans a day and execute none. Make 1 simple plan and show up for it every day.
Consistency beats motivation. Consistency beats talent.
And when you get stuck? Ask. Even if your question feels “dumb.” The dumb question you ask today is the breakthrough you needed yesterday.
Mistakes? You’ll make tons. That’s how you learn. Every bug you fight, every error you fix, becomes knowledge you’ll never forget.
Here’s the raw truth:
✨ No mentor, no tutorial, no friend can carry your dream. It’s you. Only you.
If you want it, you fight for it. You sit, you code, you fail, you repeat.
Because in the end—your future, your dream, your freedom—isn’t waiting on YouTube.
It’s waiting on your hands to type that first line of code.
⚡ Stop hiding. Start building. Even the smallest project is a step toward the life you want. ⚡
❤3
🌞 Week 5 Day 3 – Promises in JavaScript
Hello Campers! 👋✨
I hope you’re doing amazing and coding strong. Today, we step into one of the most powerful and practical features of JavaScript: Promises.
This lesson is so important because almost everything in modern JavaScript—like fetching data from an API, loading files, connecting to a database, or working with timers—depends on Promises.
So let’s slow down, break it piece by piece, and understand them deeply.
🌍 What is a Promise? (Big Picture)
👉 A Promise in JavaScript is like a commitment someone makes to you:
➤Your friend says: “I’ll bring you injera tomorrow.”
That’s a promise. Right now, you don’t have the injera, but you expect to get it.
While waiting, there are three possible outcomes:
🟡 Pending – Your friend hasn’t arrived yet (you’re still waiting).
🟢 Fulfilled – Your friend arrives with injera ✅ (promise kept).
🔴 Rejected – Your friend couldn’t bring it ❌ (promise broken).
This is exactly how JavaScript handles asynchronous tasks. A Promise is just an object that tells you:
“I might not be ready yet, but I’ll either succeed or fail in the future.”
🔑 Promise States
✅Pending – Task is still running, nothing decided yet.
✅Fulfilled (Resolved) – Task completed successfully, and we have a value.
✅Rejected – Task failed, and we have a reason (error).
🛠️ How to Create a Promise
👉 Explanation:
➤resolve() is called if the promise succeeds.
➤reject() is called if it fails.
➤But just creating a promise does nothing. We need to use it.
📦 Consuming a Promise
We use .then() and .catch() to handle the outcomes.
👉 Think of .then() as: “What should I do if my friend keeps their promise?”
👉 .catch() is: “What should I do if my friend breaks the promise?”
🍲 Real-World Analogy: Restaurant Order
Imagine you order shiro at a restaurant.
➤You place the order → Promise created (pending).
➤If the chef prepares it → resolve() (fulfilled).
➤If the restaurant runs out of shiro → reject() (rejected).
➤You (the customer) wait. When it’s ready, the waiter calls you → that’s .then().
➤If they say “Sorry, no shiro” → that’s .catch().
🔗 Promise Chaining
You can link multiple .then() calls together, where the output of one becomes the input of the next.
👉 Promise chaining is like following steps in a recipe. Each step transforms the result and passes it to the next.
🛑 Handling Errors
👉 Even if you chain multiple .then() calls, a single .catch() at the end can handle all errors in the chain.
⏳ Using Promises with setTimeout (Demo)
👉 This code waits 2 seconds, then prints:
Waited 2000 milliseconds
It’s like telling JavaScript: “Pause for 2 seconds, then let me know.”
Hello Campers! 👋✨
I hope you’re doing amazing and coding strong. Today, we step into one of the most powerful and practical features of JavaScript: Promises.
This lesson is so important because almost everything in modern JavaScript—like fetching data from an API, loading files, connecting to a database, or working with timers—depends on Promises.
So let’s slow down, break it piece by piece, and understand them deeply.
🌍 What is a Promise? (Big Picture)
👉 A Promise in JavaScript is like a commitment someone makes to you:
➤Your friend says: “I’ll bring you injera tomorrow.”
That’s a promise. Right now, you don’t have the injera, but you expect to get it.
While waiting, there are three possible outcomes:
🟡 Pending – Your friend hasn’t arrived yet (you’re still waiting).
🟢 Fulfilled – Your friend arrives with injera ✅ (promise kept).
🔴 Rejected – Your friend couldn’t bring it ❌ (promise broken).
This is exactly how JavaScript handles asynchronous tasks. A Promise is just an object that tells you:
“I might not be ready yet, but I’ll either succeed or fail in the future.”
🔑 Promise States
✅Pending – Task is still running, nothing decided yet.
✅Fulfilled (Resolved) – Task completed successfully, and we have a value.
✅Rejected – Task failed, and we have a reason (error).
🛠️ How to Create a Promise
let myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) { resolve("🎉 Task completed successfully!"); }
else { reject("❌ Something went wrong!");
} }); 👉 Explanation:
➤resolve() is called if the promise succeeds.
➤reject() is called if it fails.
➤But just creating a promise does nothing. We need to use it.
📦 Consuming a Promise
We use .then() and .catch() to handle the outcomes.
myPromise .then(result => {
console.log(result); // 🎉 Task completed successfully! })
.catch(error => { console.log(error); // ❌ Something went wrong! }); 👉 Think of .then() as: “What should I do if my friend keeps their promise?”
👉 .catch() is: “What should I do if my friend breaks the promise?”
🍲 Real-World Analogy: Restaurant Order
Imagine you order shiro at a restaurant.
➤You place the order → Promise created (pending).
➤If the chef prepares it → resolve() (fulfilled).
➤If the restaurant runs out of shiro → reject() (rejected).
➤You (the customer) wait. When it’s ready, the waiter calls you → that’s .then().
➤If they say “Sorry, no shiro” → that’s .catch().
🔗 Promise Chaining
You can link multiple .then() calls together, where the output of one becomes the input of the next.
let step1 = new Promise((resolve, reject) => {
resolve(2); });
step1 .then(num => {
console.log("First result:", num);
return num * 2; // Passes 4 to next then })
.then(num => {
console.log("Second result:", num);
return num * 3; // Passes 12 to next then })
.then(num => {
console.log("Final result:", num); // 12 }); 👉 Promise chaining is like following steps in a recipe. Each step transforms the result and passes it to the next.
🛑 Handling Errors
let riskyTask = new Promise((resolve, reject) => {
let value = Math.random();
if (value > 0.5) { resolve("✅ Success! Value: " + value); }
else { reject("❌ Failure! Value: " + value); } });
riskyTask
.then(res => console.log(res))
.catch(err => console.log(err));
👉 Even if you chain multiple .then() calls, a single .catch() at the end can handle all errors in the chain.
⏳ Using Promises with setTimeout (Demo)
function wait(ms) { return new Promise(resolve => {
setTimeout(() => { resolve(Waited ${ms} milliseconds); }, ms);
}); }
wait(2000).then(message => console.log(message));
👉 This code waits 2 seconds, then prints:
Waited 2000 milliseconds
It’s like telling JavaScript: “Pause for 2 seconds, then let me know.”
🤯 Why Promises?
➤Before Promises, developers had to use nested callbacks (callback hell). ➤Promises clean that mess and make code more readable and maintainable.
Instead of:
Much cleaner ✅
💡 Summary
✅A Promise represents a future result of an asynchronous task.
✅It can be pending, fulfilled, or rejected.
✅Use .then() for success and .catch() for errors.
✅Promises can be chained for sequential tasks.
✅They help us avoid messy callback hell.
➤Before Promises, developers had to use nested callbacks (callback hell). ➤Promises clean that mess and make code more readable and maintainable.
Instead of:
We can write:task1(() => {
task2(() => {
task3(() => { console.log("Done!"); }); }); });
task1()
.then(task2)
.then(task3)
.then(() => console.log("Done!"))
.catch(err => console.log(err)); Much cleaner ✅
💡 Summary
✅A Promise represents a future result of an asynchronous task.
✅It can be pending, fulfilled, or rejected.
✅Use .then() for success and .catch() for errors.
✅Promises can be chained for sequential tasks.
✅They help us avoid messy callback hell.
🔥 Extra Promise Examples
1️⃣ Delayed Message Example
Imagine you want to show a greeting after 3 seconds.
👉 Explanation:
delayedMessage() returns a Promise.
After time (3000ms = 3s), the message is resolved.
.then() receives the final value and logs it.
2️⃣ Random Weather Reporter
Let’s pretend we’re building a weather service 🌦️
👉 Explanation:
➤80% chance to get a random weather report.
➤20% chance to reject with an error.
➤Shows how Promises handle both success and failure cases.
3️⃣ Promise Chaining: Coffee Order ☕
You order coffee → they prepare → they deliver.
👉 Explanation:
Each .then() returns a new value → passed to the next .then().
It’s like following steps in real-world tasks.
4️⃣ Simulating an Online Exam Result 📝
👉 Explanation:
➤If the score is 50 or above → Promise resolves.
➤Otherwise → Promise rejects.
A simple way to show yes/no outcomes.
5️⃣ Running Multiple Promises Together
Promise.all()
Wait for all tasks to finish.
👉 Explanation:
➤Promise.all() waits until all promises are resolved.
➤Returns an array of results.
Promise.race()
Who finishes first? 🏁
👉 Explanation:
➤Promise.race() returns the result of the first resolved promise.
Great analogy: runners in a race.
✅ With these extra examples, you can see how Promises:
➤Delay things (timers)
➤Represent real-world uncertain tasks (weather, exam results)
➤Can chain steps (coffee order)
➤Can run multiple tasks together (all, race)
1️⃣ Delayed Message Example
Imagine you want to show a greeting after 3 seconds.
function delayedMessage(msg, time) {
return new Promise(resolve => {
setTimeout(() => { resolve(msg); }, time); }); }
delayedMessage("👋 Hello campers!", 3000)
.then(res => console.log(res));
👉 Explanation:
delayedMessage() returns a Promise.
After time (3000ms = 3s), the message is resolved.
.then() receives the final value and logs it.
2️⃣ Random Weather Reporter
Let’s pretend we’re building a weather service 🌦️
function getWeather() { return new Promise((resolve, reject) => {
let weather = ["☀️ Sunny", "🌧️ Rainy", "⛅ Cloudy"];
let random = Math.random();
if (random > 0.2) { resolve(weather[Math.floor(Math.random() * weather.length)]); }
else { reject("❌ Weather service unavailable"); } }); }
getWeather()
.then(res => console.log("Today’s weather:", res))
.catch(err => console.log(err));
👉 Explanation:
➤80% chance to get a random weather report.
➤20% chance to reject with an error.
➤Shows how Promises handle both success and failure cases.
3️⃣ Promise Chaining: Coffee Order ☕
You order coffee → they prepare → they deliver.
function orderCoffee() { return new Promise(resolve => {
resolve("✅ Order placed"); }); }
orderCoffee()
.then(msg => {
console.log(msg);
return "☕ Coffee is being prepared"; })
.then(msg => {
console.log(msg);
return "🚚 Coffee is on the way"; })
.then(msg => {
console.log(msg);
return "🎉 Coffee delivered!"; })
.then(final => console.log(final));
👉 Explanation:
Each .then() returns a new value → passed to the next .then().
It’s like following steps in real-world tasks.
4️⃣ Simulating an Online Exam Result 📝
function checkResult(score) { return new Promise((resolve, reject) => {
if (score >= 50) { resolve("🎉 You passed with " + score + "%"); }
else { reject("❌ You failed with " + score + "%"); } }); }
checkResult(72)
.then(res => console.log(res))
.catch(err => console.log(err));
👉 Explanation:
➤If the score is 50 or above → Promise resolves.
➤Otherwise → Promise rejects.
A simple way to show yes/no outcomes.
5️⃣ Running Multiple Promises Together
Promise.all()
Wait for all tasks to finish.
let promise1 = new Promise(resolve => setTimeout(() => resolve("✅ Task 1 done"), 1000));
let promise2 = new Promise(resolve => setTimeout(() => resolve("✅ Task 2 done"), 2000));
Promise.all([promise1, promise2])
.then(results => console.log("All tasks finished:", results)); 👉 Explanation:
➤Promise.all() waits until all promises are resolved.
➤Returns an array of results.
Promise.race()
Who finishes first? 🏁
let fast = new Promise(resolve => setTimeout(() => resolve("⚡ Fast task finished"), 1000));
let slow = new Promise(resolve => setTimeout(() => resolve("🐢 Slow task finished"), 3000));
Promise.race([fast, slow])
.then(result => console.log(result));
👉 Explanation:
➤Promise.race() returns the result of the first resolved promise.
Great analogy: runners in a race.
✅ With these extra examples, you can see how Promises:
➤Delay things (timers)
➤Represent real-world uncertain tasks (weather, exam results)
➤Can chain steps (coffee order)
➤Can run multiple tasks together (all, race)