BRAINBIT INFOTECH · RANCHI
COMPLETE JAVASCRIPT COURSE · PART 3 OF 4

Advanced JavaScript

Timers, saving data, asynchronous code, real APIs and modern ES6+ syntax used in every professional project.

5 modules~16.5 hours25 practice examplesNeeds Parts 1-2

By the end of this part you can build

  • A countdown timer, digital clock and image slider
  • Notes and settings that survive a refresh
  • A weather app and a student list loaded from an API
  • Clean, modern, crash-proof code

Every example opens in a live browser preview. Click ✎ Edit on any preview, or press L, to open the Code Lab.

ROADMAP FOR THIS PART

Module 13Timers, Dates & Animation3 h
Module 14localStorage: Apps That Remember2.5 h
Module 15Async JS: Callbacks, Promises, async/await4 h
Module 16Fetch & APIs3.5 h
Module 17Modern ES6+ & Error Handling3.5 h
JavaScriptBefore we begin

How to Use This Part

Suggested teaching hours per module (Part 3)012353 hM132.5 hM144 hM153.5 hM163.5 hM17

Every module has

  1. 1
    A "Where is it used?" diagram of a real web page
  2. 2
    Concept slides with code + live preview + console
  3. 3
    Step-through animations: watch variables change
  4. 4
    A Live Lab: edit code, see the result instantly
  5. 5
    5 practice examples with solutions
  6. 6
    An animated recap + quiz
Controls→ next, ← back, M menu, L Code Lab, F fullscreen. Click ✎ Edit on any preview to change its code.
MODULE 13

Timers, Dates & Animation

⏱ 3 hours5 practice examplesLive code lab

You will learn

  • setTimeout: run code later
  • setInterval and clearInterval: repeat and stop
  • The Date object: today, time, formatting in Indian style
  • Date maths: days left, age, countdowns
  • Smooth animation with requestAnimationFrame

You will build

  • A digital clock
  • An exam countdown timer
  • An auto-playing image slider
setInterval(tick, 1000)
Module 13Real-world use

Where Is This Used in Real Websites and Apps?

LOGOHero bannerHeaderButtonCards / boxes

You will find it here

  • Sliders / carousels that change every few seconds
  • Countdowns: sale ends in 02:15:09, OTP expires in 30 s
  • Clocks, "posted 5 minutes ago" labels
  • Toasts that disappear after 3 seconds
  • Auto-save every 30 seconds, live score refresh
Module 13setTimeout

setTimeout: Run Code After a Delay

script.jsJS
Press Next step to run the program one line at a time.

Memory (variables)

(empty)

Console output

Non-blockingTimers do not freeze the page. The user can keep scrolling and clicking while JS waits. (Why? See the Event Loop in Module 15.)
Module 13setInterval

setInterval and clearInterval: Repeat and Stop

D:/js-practice/timer.html
Console output appears here
FunctionDoes
setTimeout(fn, ms)run once after ms
setInterval(fn, ms)run every ms, forever
clearInterval(id)stop an interval
clearTimeout(id)cancel a timeout before it runs
Common bugClicking Start twice creates TWO intervals, and the counter goes double speed. Always guard with if (timerId) return;
1000 ms = 1 secondTimers are not perfectly exact; for clocks, read the real time from Date each tick.
Module 13Dates

The Date Object: Today, Time and Indian Formats

script.jsJS
D:/js-practice/script.js
Console output appears here
Month trapgetMonth() returns 0 for January and 11 for December. Add 1 to display it.
Hindi dates"hi-IN" prints weekday and month names in Hindi automatically.
Module 13Date maths

Date Maths: Days Left, Age, "Posted 5 min ago"

script.jsJS
D:/js-practice/script.js
Console output appears here
Dates are numbersSubtracting two dates gives milliseconds. Divide by 1000, 60, 60, 24 to get days.
Module 13Animation

requestAnimationFrame: Smooth 60 fps Animation

D:/js-practice/animate.html
Console output appears here
Typical smoothness (frames per second)01835527050 fpssetInterval(16 ms)60 fpsrequestAnimationFrame60 fpsCSS transition

Illustrative: rAF syncs with the screen refresh and pauses in hidden tabs.

animate.jsJS
Prefer CSSFor simple moves use CSS transitions/animations. Use requestAnimationFrame for games, charts and physics.
Module 13Live Lab

Live Lab: A Digital Clock

clock.html – edit me!
Live preview
TryShow 24-hour time with { hour12: false }. Add a greeting (Good morning/evening). Show the date in Hindi with "hi-IN".
Module 13Practice Example 1 of 5

Digital Clock with Greeting

BeginnerA reception screen at BrainBit Infotech shows the time, date and a greeting.

Your tasks

  1. tick() reads new Date() and updates the page
  2. setInterval(tick, 1000), and call tick() once at the start
  3. Time padded to 2 digits: String(n).padStart(2, "0")
  4. Greeting by hour (morning/afternoon/evening)
  5. Blinking colon using a CSS class toggled every second
Where this is used: Dashboards, kiosks, attendance and token displays.
clock.htmlHTML
Module 13Practice Example 2 of 5

Exam Countdown Timer

IntermediateShow a countdown to the JAC Board exam: days, hours, minutes and seconds left.

Your tasks

  1. Target date (e.g. 15 February next year, 10:00 AM)
  2. Every second: difference = target - now
  3. Convert ms to days, hours, minutes, seconds with Math.floor and %
  4. Show 4 boxes with padded numbers
  5. When time is up, clearInterval and show "All the best!"
Where this is used: Sale countdowns, event launches, OTP expiry, quiz timers.
countdown.htmlHTML
Module 13Practice Example 3 of 5

Auto-Playing Image Slider

IntermediateThe Jharkhand tourism homepage slider changes the photo every 3 seconds, with dots and prev/next buttons.

Your tasks

  1. Array of slides {img, title}
  2. show(index) updates image, caption and active dot
  3. setInterval moves to the next slide (wrap around with %)
  4. Prev/Next buttons; restart the timer when clicked
  5. Pause on mouse hover
Where this is used: Homepage banners, product photo carousels, testimonials.
slider.htmlHTML
Module 13Practice Example 4 of 5

Stopwatch with Laps

IntermediateA sports-day stopwatch: Start, Stop, Reset and Lap, showing minutes:seconds.hundredths.

Your tasks

  1. Store startTime and elapsed ms (do not just count ticks)
  2. setInterval(update, 10) while running
  3. Format mm:ss.cc
  4. Lap button adds the current time to a list
  5. Reset clears everything
HintCounting ticks drifts over time. Measuring with Date.now() is always accurate.
Where this is used: Fitness apps, online exam timers, games.
stopwatch.htmlHTML
Module 13Practice Example 5 of 5

OTP Resend Timer

BeginnerAfter sending an OTP, the "Resend OTP" button is disabled for 30 seconds with a live countdown.

Your tasks

  1. Button "Resend OTP" disabled at the start
  2. seconds = 30; setInterval every 1000 ms
  3. Show "Resend in 29s", "28s"...
  4. At 0: clearInterval, enable the button
  5. Clicking resend restarts the 30 s timer and logs a new OTP
Where this is used: Login, payment and sign-up verification screens.
otp-timer.htmlHTML
Module 13Module complete

Recap: What You Completed in Module 13

  • ✓setTimeout runs code later (non-blocking)
  • ✓setInterval repeats; clearInterval stops
  • ✓Guard against starting twice
  • ✓Date: get parts, month starts at 0
  • ✓toLocaleDateString("en-IN" / "hi-IN")
  • ✓Date maths: subtract dates for days left, age, time ago
  • ✓requestAnimationFrame for smooth animation
100%Module 13 done

Coming next

Module 14: localStorage – make your apps remember data after a refresh.

Quick quiz – click an answer

Q1. What prints first?
setTimeout(() => log("A"), 0); log("B");

Timers always wait until the current code finishes.

Q2. How to stop const id = setInterval(f, 1000)?

Pass the id to clearInterval.

Q3. new Date(2026, 0, 26) is:

Month 0 = January.
MODULE 14

localStorage: Apps That Remember

⏱ 2.5 hours5 practice examplesLive code lab

You will learn

  • Why data disappears on refresh
  • localStorage: setItem, getItem, removeItem, clear
  • Saving arrays and objects with JSON
  • sessionStorage vs localStorage vs cookies
  • Safe loading with defaults and try...catch

You will build

  • A theme that is remembered
  • A notes app that survives refresh
  • A visit counter and a saved cart
theme: "dark"todos: [...]lang: "hi"score: 120localStorage
Module 14Real-world use

Where Is This Used in Real Websites and Apps?

LOGOHeaderCards / boxesFormButton

You will find it here

  • Dark / light theme remembered next time you visit
  • Cart items still there after closing the tab
  • Form drafts so a long application is not lost
  • Game high scores, "recently viewed" products
  • Language choice: Hindi or English
Module 14Why storage?

Variables Forget, localStorage Remembers

JS variableslet todos = [...]lost on refresh! localStorage"todos": "[...]"kept after refreshand after closing setItem(key, JSON.stringify(data)) JSON.parse(getItem(key)) Stored in YOUR browser, per website. About 5 MB. Only strings.
script.jsJS
D:/js-practice/script.js
Console output appears here
MethodDoes
setItem(k, v)save (value becomes text)
getItem(k)read, or null
removeItem(k)delete one
clear()delete everything for this site
Module 14Objects & arrays

Saving Arrays and Objects with JSON

script.jsJS
D:/js-practice/script.js
Console output appears here
The two magic linesSave: localStorage.setItem("k", JSON.stringify(data))
Load: JSON.parse(localStorage.getItem("k")) || default
Module 14Remember settings

Remember the Theme and Count Visits

D:/js-practice/theme.html
Console output appears here
Try itToggle the theme, then click ↻ Run to reload the page. The theme stays, and the visit count goes up.
theme.jsJS
Pattern1) On page load: read storage and apply. 2) On every change: write storage.
Module 14Which storage?

localStorage vs sessionStorage vs Cookies

localStoragesessionStorageCookies
Lastsuntil deleteduntil the tab closesuntil expiry date
Size~5 MB~5 MB~4 KB
Sent to server?nonoyes, with every request
Good fortheme, cart, drafts, notesone-time form stepslogin sessions (set by server)
Read withlocalStorage.getItemsessionStorage.getItemdocument.cookie
Never store secretsDo not save passwords, OTPs or card numbers in localStorage. Any script on the page can read it.
See it in DevToolsF12 > Application tab > Local Storage > your site. You can view, edit and delete keys.
Module 14Safe loading

Load Data Safely: Defaults and try...catch

script.jsJS
D:/js-practice/script.js
Console output appears here
Reusable helpersPut loadJSON / saveJSON in every project. JSON.parse throws an error on bad text; try...catch (Module 17) keeps the app running.
Module 14Live Lab

Live Lab: An Auto-Saving Notepad

notes.html – edit me!
Live preview
TryType, then press ↻ Run: the note is still there. Add a "Clear" button that uses removeItem. Show a word count.
Module 14Practice Example 1 of 5

Remembered Language Choice

BeginnerA Jharkhand government info page can switch between Hindi and English, and remembers the choice.

Your tasks

  1. Two buttons: English, हिंदी
  2. An object with texts for "en" and "hi"
  3. setLang(code) updates the page and saves "lang"
  4. On load: setLang(saved language or "en")
  5. Highlight the active button
Where this is used: Multilingual government and news sites, app settings.
language.htmlHTML
Module 14Practice Example 2 of 5

Notes App That Survives Refresh

IntermediateA notes app: add notes with a title, delete them, and keep everything in localStorage.

Your tasks

  1. notes array loaded with loadJSON("notes", [])
  2. Add form pushes {id: Date.now(), text, date}
  3. save() after every change, then render()
  4. Delete button removes by id with filter
  5. Show the date each note was written
HintDate.now() is a handy unique id: the number of milliseconds since 1970.
Where this is used: Notes apps, journals, saved searches.
notes.htmlHTML
Module 14Practice Example 3 of 5

Saved Shopping Cart

IntermediateMake the Ranchi Mart cart survive a refresh: products can be added; the cart count and list are stored.

Your tasks

  1. cart = loadJSON("cart", [])
  2. Add buttons push or increase qty
  3. save + render after each change
  4. Header badge shows total items
  5. "Clear cart" button with removeItem
Where this is used: Every shopping site keeps your cart between visits.
saved-cart.htmlHTML
Module 14Practice Example 4 of 5

Form Draft Auto-Save

IntermediateA long scholarship application should not lose what the student typed if the browser closes.

Your tasks

  1. Form with name, school, city and an essay
  2. On any input: save all fields as one object (FormData)
  3. On load: fill the fields from the saved draft
  4. Show "Draft saved" with the time
  5. On submit: remove the draft
Where this is used: Job and exam applications, email drafts, long surveys.
draft.htmlHTML
Module 14Practice Example 5 of 5

High Score for a Reaction Game

AdvancedA reaction-time game: wait for the box to turn green, click fast. The best time is saved as the high score.

Your tasks

  1. Click "Start": box turns red, then green after a random 1-4 s (setTimeout)
  2. Measure time from green to click with Date.now()
  3. Clicking too early shows "Too soon!"
  4. Best (lowest) time saved in localStorage
  5. Show "New record!" when beaten
Where this is used: Game high scores, streaks, achievements.
reaction.htmlHTML
Module 14Module complete

Recap: What You Completed in Module 14

  • ✓Variables reset on refresh; storage keeps data
  • ✓setItem, getItem, removeItem, clear
  • ✓Everything is stored as text
  • ✓JSON.stringify to save, JSON.parse to load
  • ✓Load on start, save on every change
  • ✓localStorage vs sessionStorage vs cookies
  • ✓Safe loading with defaults and try...catch; no secrets
100%Module 14 done

Coming next

Module 15: Async JavaScript – callbacks, promises, async/await and the event loop.

Quick quiz – click an answer

Q1. localStorage.getItem("age") after setItem("age", 15) returns:

localStorage stores only strings.

Q2. How do you save an array?

Convert to JSON text first.

Q3. Should passwords be saved in localStorage?

Any script on the page can read it.
MODULE 15

Async JS: Callbacks, Promises, async/await

⏱ 4 hours5 practice examplesLive code lab

You will learn

  • Synchronous vs asynchronous code
  • Callbacks and "callback hell"
  • Promises: pending, fulfilled, rejected; then / catch
  • async / await with try...catch
  • The event loop; Promise.all for parallel tasks

You will build

  • A fake "order tracking" with steps
  • A promise-based delay() helper
  • A loading spinner while data loads
CALL STACK WEB APIs (browser) CALLBACK QUEUE main() timer 2s fetch(...) onTimer() onData() EVENT LOOP:when the stack is empty,move the next callbackfrom the queue to the stack JS does one thing at a time; the browser waits for timers and network in the background.
Module 15Real-world use

Where Is This Used in Real Websites and Apps?

LOGOCards / boxesButtonForm

You will find it here

  • Loading data from a server: products, weather, scores
  • Payments: wait for the bank to reply
  • Uploading photos, sending chat messages
  • Spinners shown while waiting
  • Anything that takes time must be async, or the page would freeze
Module 15Sync vs async

Synchronous vs Asynchronous: the Chai Shop Story

1

Synchronous (one by one)

The chaiwala takes your order, makes your chai, waits for it to boil, gives it to you... and only THEN takes the next order. The queue grows!
2

Asynchronous (smart)

He puts your chai on the stove (background work), takes the next order, and serves each chai when it is ready. Nobody waits for nothing.
In JavaScriptTimers, fetch (network), reading files: the browser does them in the background and calls your function back when done.
script.jsJS
D:/js-practice/script.js
Console output appears here
Module 15Event loop

The Event Loop: How JS Does Many Things

CALL STACK WEB APIs (browser) CALLBACK QUEUE main() timer 2s fetch(...) onTimer() onData() EVENT LOOP:when the stack is empty,move the next callbackfrom the queue to the stack JS does one thing at a time; the browser waits for timers and network in the background.
Module 15Event loop

Step Through the Event Loop

script.jsJS
Press Next step to run the program one line at a time.

Where things are

(empty)

Console output

Module 15Callbacks

Callbacks and "Callback Hell"

callback-hell.jsJS
ProblemsHard to read (the pyramid), hard to handle errors at every level, hard to change. Promises fix this.
script.jsJS
D:/js-practice/script.js
Console output appears here
Module 15Promises

A Promise: "I Will Give You the Result Later"

PENDINGwaiting for result FULFILLEDresolve(value) → .then REJECTEDreject(error) → .catch
Like an online orderOrder placed = pending. Delivered = fulfilled. Cancelled = rejected. You get a receipt (the promise) immediately.
script.jsJS
D:/js-practice/script.js
Console output appears here
Module 15Chaining

Promise Chaining: No More Pyramid

script.jsJS
D:/js-practice/script.js
Console output appears here
  • Each .then can return a new promise; the next .then waits for it
  • One .catch at the end handles an error from ANY step
  • Code reads top to bottom like a list of steps
Module 15async / await

async / await: Async Code That Reads Like Normal Code

script.jsJS
D:/js-practice/script.js
Console output appears here
Rule
async before functionit always returns a promise
await promisepause THIS function until it settles
Errorsuse try...catch
Only inside async(or at the top level of modules)
Same thing, nicerasync/await is just a cleaner way to write .then chains. Modern code (and Module 16 fetch) uses it everywhere.
Module 15Parallel

Promise.all: Do Several Things at the Same Time

script.jsJS
D:/js-practice/script.js
Console output appears here
Time to load 3 things (ms)one by one2400 msPromise.all800 ms
AlsoPromise.race = first to finish wins (timeouts). Promise.allSettled = wait for all even if some fail.
Module 15Live Lab

Live Lab: Live Order Tracking with await

tracking.html – edit me!
Live preview
TryMake each step take a random time (500-2000 ms). Add a 5th step "Rate your order". Show a progress percentage.
Module 15Practice Example 1 of 5

A delay() Helper and a Countdown

BeginnerWrite a reusable delay(ms) that returns a promise, and use it to count down 3, 2, 1, Go! for a quiz start screen.

Your tasks

  1. const delay = ms => new Promise(r => setTimeout(r, ms))
  2. async function start()
  3. Loop 3 to 1 with await delay(1000)
  4. Update a big number on the page
  5. Show "Go!" and log the total time
Where this is used: Animations in sequence, retry with waiting, games.
delay.htmlHTML
Module 15Practice Example 2 of 5

Simulated Payment with Success / Failure

IntermediateSimulate a UPI payment: a promise that succeeds 70% of the time after 1.5 s. Show a spinner while waiting.

Your tasks

  1. pay(amount) returns a Promise
  2. Math.random() < 0.7 → resolve with a transaction id, else reject with an Error
  3. Button click: show spinner, disable button
  4. await inside try / catch / finally
  5. Show green success or red failure; re-enable button in finally
Where this is used: Payment pages, OTP verification, any action waiting for a server.
payment.htmlHTML
Module 15Practice Example 3 of 5

Callbacks to Promises Refactor

IntermediateRewrite a callback pyramid (book ticket → choose seat → pay) using promises and async/await.

Your tasks

  1. Three functions that return promises with delays
  2. Version 1: .then chain
  3. Version 2: async/await
  4. One catch for all errors
  5. Make chooseSeat fail for seat "13" to test the error path
Where this is used: Every real codebase is moving from callbacks to async/await.
refactor.jsJS
Module 15Practice Example 4 of 5

Loading Spinner While "Data" Loads

IntermediateA results page shows a skeleton loader for 1.5 s while fake data loads, then shows the list.

Your tasks

  1. fakeFetch() returns a promise with an array after 1.5 s
  2. Show grey animated skeleton rows first
  3. await the data, then render it
  4. Handle an empty result
  5. Reload button runs it again
Where this is used: YouTube, LinkedIn and Facebook skeleton loaders.
skeleton.htmlHTML
Module 15Practice Example 5 of 5

Parallel Loading with Promise.all

AdvancedA student dashboard needs profile, attendance and fees. Load them in parallel and show the total load time.

Your tasks

  1. Three fake API functions with different delays
  2. Promise.all to load together
  3. Destructure the three results
  4. Show each in a card
  5. Compare with loading one by one (show both times)
Where this is used: Dashboards that call several APIs at once.
dashboard.htmlHTML
Module 15Module complete

Recap: What You Completed in Module 15

  • ✓Sync = one at a time; async = wait in the background
  • ✓Event loop: call stack, Web APIs, queues
  • ✓Callbacks and callback hell
  • ✓Promises: pending, fulfilled, rejected
  • ✓.then / .catch / .finally chains
  • ✓async / await with try...catch
  • ✓Promise.all for parallel work
100%Module 15 done

Coming next

Module 16: Fetch & APIs – load real data from servers.

Quick quiz – click an answer

Q1. Output order of log(1); setTimeout(()=>log(2),0); log(3)?

The timer callback waits for the current script to finish.

Q2. Where can you use await?

await only works in async functions (or module top level).

Q3. A rejected promise is handled with:

catch receives the error.
MODULE 16

Fetch & APIs

⏱ 3.5 hours5 practice examplesLive code lab

You will learn

  • What an API is; URLs, endpoints and query parameters
  • fetch() with async/await and response.json()
  • Status codes: 200, 404, 500 and error handling
  • Loading, success, error and empty states
  • Sending data with POST; search with debouncing

You will build

  • A weather app
  • A student list from a server
  • A product search and a feedback form that POSTs
YOUR APPfetch(url)📱 API SERVER/api/weather🗄 GET ?city=ranchi 200 OK {"temp":24} 1. REQUEST2. RESPONSE (JSON) API = a door into another program. You ask in a fixed format, it answers with data.
Module 16Real-world use

Where Is This Used in Real Websites and Apps?

LOGOCards / boxesFormListHeader

You will find it here

  • Weather widgets, live cricket scores, stock prices
  • Shopping sites load products from their API
  • Login sends your details to an auth API
  • Maps, payments (UPI), SMS: all are APIs
  • Every mobile app talks to servers through APIs
In this deckThe previews include a practice server: /api/students, /api/products, /api/weather?city=ranchi, /api/quiz, /api/posts, /api/users/1, /api/error, /api/slow. It works offline.
Module 16APIs

How fetch Talks to a Server

YOUR APPfetch(url)📱 API SERVER/api/weather🗄 GET ?city=ranchi 200 OK {"temp":24} 1. REQUEST2. RESPONSE (JSON) API = a door into another program. You ask in a fixed format, it answers with data.
https://api.brainbit.exampleserver
/api/weatherendpoint (path)
?city=ranchiquery parameter
&units=metricanother parameter
Module 16First fetch

Your First fetch: Load a List of Students

script.jsJS
D:/js-practice/script.js
Console output appears here
  1. 1
    fetch(url) returns a promise of a Response
  2. 2
    await it to get status and headers
  3. 3
    await response.json() to read the data
  4. 4
    Then use the data: render it on the page
Two awaitsForgetting the second await gives you Promise {<pending>} instead of data.
Module 16Status codes

Status Codes and Error Handling

script.jsJS
D:/js-practice/script.js
Console output appears here
CodeMeansShow the user
200 OKsuccessthe data
201 Createdsaved (after POST)"Saved!"
400 Bad Requestwrong inputfix the form
401 / 403not logged in / not allowedlogin page
404 Not Foundno such thing"Not found"
500 Server Errorserver problem"Try again later"
fetch quirkfetch only rejects on network failure. A 404 or 500 still "succeeds", so always check res.ok.
Module 16UI states

The 4 States Every Data Screen Needs

D:/js-practice/states.html
Loading
spinner / skeleton
Success
show data
Empty
"no results"
Error
message + retry
states.jsJS
Module 16POST

Sending Data with POST

script.jsJS
D:/js-practice/script.js
Console output appears here
MethodUsed for
GETread data (default)
POSTcreate: sign up, place order, send message
PUT / PATCHupdate: edit profile
DELETEremove: delete a post
Practice serverAny POST to the practice server echoes your data back with a new id and status 201.
Module 16Live Lab

Live Lab: Load Posts from the API

posts.html – edit me!
Live preview
TrySort posts by likes (most first). Change the URL to /api/students and show names with marks. Try /api/error to see the error message.
Module 16Practice Example 1 of 5

Weather App

IntermediateType a Jharkhand city and see its weather (practice API: /api/weather?city=NAME; try Ranchi, Dhanbad, Netarhat, Patna).

Your tasks

  1. Input + Search button (and Enter key)
  2. Build the URL with encodeURIComponent
  3. Show loading text while waiting
  4. On 404 show "City not found"
  5. Show temperature, condition, humidity and wind in a card with an icon
HintFor a real app, use a free weather API (for example Open-Meteo) – only the URL and field names change.
Where this is used: Weather widgets on news and travel sites.
weather.htmlHTML
Module 16Practice Example 2 of 5

Student List from the Server

BeginnerLoad /api/students and show a table sorted by marks, with a "topper" highlight.

Your tasks

  1. async function with fetch and res.json()
  2. Sort by marks high to low
  3. Render a table with rank
  4. Highlight the top student
  5. Show an error row if the request fails
Where this is used: Admin panels, school ERPs, any list from a database.
students.htmlHTML
Module 16Practice Example 3 of 5

Product Search with Debounce

AdvancedSearch products as you type (/api/products?q=TEXT), but wait 400 ms after the user stops typing before calling the server.

Your tasks

  1. debounce(fn, ms): clearTimeout + setTimeout
  2. On input: debounced search(query)
  3. Show "Searching..." and then cards
  4. Empty state "No products match"
  5. Log how many requests were actually sent
HintWithout debounce, typing "saree" sends 5 requests. With it, only 1.
Where this is used: Search bars on Amazon, Swiggy, YouTube.
search.htmlHTML
Module 16Practice Example 4 of 5

Feedback Form that POSTs JSON

IntermediateSend course feedback to /api/feedback with POST, then show the saved record returned by the server.

Your tasks

  1. Form: name, rating (1-5 select), comment
  2. submit + preventDefault
  3. fetch with method POST, JSON headers and body
  4. Disable the button while sending
  5. Show "Thank you! Feedback #ID saved" from the response
Where this is used: Contact forms, reviews, sign-ups that save to a database.
feedback.htmlHTML
Module 16Practice Example 5 of 5

Quiz Loaded from an API

AdvancedLoad questions from /api/quiz and run a one-question-at-a-time quiz with score.

Your tasks

  1. Fetch questions on start (loading state)
  2. Show question and option buttons
  3. On click: mark right (green) or wrong (red), then next after 800 ms
  4. Score counter
  5. Final screen with score and "Play again"
Where this is used: Online tests, learning apps, trivia games.
api-quiz.htmlHTML
Module 16Module complete

Recap: What You Completed in Module 16

  • ✓API = asking another program for data
  • ✓URL, endpoint, query parameters
  • ✓await fetch(url) then await res.json()
  • ✓Check res.ok; handle 404 / 500 in try...catch
  • ✓Loading, success, empty and error states
  • ✓POST with method, headers, JSON body
  • ✓Debounce search requests
100%Module 16 done

Coming next

Module 17: Modern ES6+ syntax and error handling.

Quick quiz – click an answer

Q1. What does await res.json() give?

It reads the body and parses JSON.

Q2. A 404 response makes fetch:

Always check res.ok yourself.

Q3. To create a new record on a server use:

POST sends data to create something.
MODULE 17

Modern ES6+ & Error Handling

⏱ 3.5 hours5 practice examplesLive code lab

You will learn

  • let/const, arrow functions and template literals (review)
  • Destructuring, spread and rest in depth
  • Optional chaining ?. and nullish coalescing ??
  • Map, Set, short object syntax, modern array helpers
  • try / catch / finally, throw and custom errors

You will build

  • A config merger with spread and defaults
  • A safe API data reader with ?. and ??
  • A crash-proof calculator with custom errors
...spread{ a, b } =?.??try / catch`${x}`
Module 17Real-world use

Where Is This Used in Real Websites and Apps?

LOGOWhole page

You will find it here

  • Every modern codebase (React, Node.js, Vue) is written with ES6+ syntax
  • ?. and ?? stop crashes when API data is missing
  • Spread copies and updates state in React
  • try / catch keeps apps running when something fails
  • Job interviews ask about these features
ES6?ECMAScript 2015 (ES6) was the big upgrade of JavaScript. New features are added every year (ES2016, ES2017...). Together we call them "modern JS".
Module 17Old vs new

Old JavaScript vs Modern JavaScript

old.jsJS
modern.jsJS
Same resultsBoth do the same work. Modern code is shorter, clearer and has fewer bugs.
Module 17Spread & rest

Spread ... and Rest ...: Same Dots, Two Jobs

script.jsJS
D:/js-practice/script.js
Console output appears here
WhereNameDoes
In a call / array / object literalspreadopens the box
In parameters / destructuringrestpacks the leftovers
Module 17?. and ??

Optional Chaining ?. and Nullish Coalescing ??

script.jsJS
D:/js-practice/script.js
Console output appears here
Real APIsServer data often has missing fields. ?. stops the crash; ?? gives a sensible default.
|| vs ??|| replaces 0, "" and false too. ?? only replaces null and undefined.
Module 17Handy features

Short Object Syntax, Map, Set and Modern Helpers

script.jsJS
D:/js-practice/script.js
Console output appears here
Module 17Errors

try / catch / finally: Errors Without Crashing

script.jsJS
Press Next step to run the program one line at a time.

Memory (variables)

(empty)

Console output

Module 17throw

throw and Custom Errors: Your Own Rules

script.jsJS
D:/js-practice/script.js
Console output appears here
Built-in errorTypical cause
ReferenceErrorvariable not defined
TypeErrorwrong type, null.something
SyntaxErrorbad code or bad JSON
RangeErrornumber out of range
Classesclass ... extends Error is explained in Module 18.
Module 17Live Lab

Live Lab: Safe Data with ?. ?? and Destructuring

safe-data.html – edit me!
Live preview
TryRemove the ?. from address?.city and read the error. Add a user with no name and default it to "Guest". Use spread to add role: "student" to every user.
Module 17Practice Example 1 of 5

Settings Merger with Spread and Defaults

BeginnerAn app has default settings; each user saves only what they changed. Merge them correctly.

Your tasks

  1. defaults object (theme, lang, fontSize, notifications)
  2. userSettings object with 2 changes
  3. final = {...defaults, ...userSettings}
  4. A function update(settings, changes) that returns a NEW object
  5. Prove the original is unchanged
Where this is used: App settings, React state updates, config files.
settings.jsJS
Module 17Practice Example 2 of 5

Safe API Data Reader

IntermediateData from a delivery API is incomplete. Print a clean summary for every order without crashing.

Your tasks

  1. Array of orders where some have no rider, no address or no rating
  2. Use ?. for nested fields
  3. Use ?? for defaults
  4. Destructure in the map callback
  5. Count orders that still need a rider
HintOrder 2 has rating 0. With || it would wrongly show "-"; ?? keeps the 0.
Where this is used: Every app that reads API responses.
safe-orders.jsJS
Module 17Practice Example 3 of 5

Crash-Proof Calculator

IntermediateA calculator page that never crashes: invalid input or division by zero shows a friendly message.

Your tasks

  1. Two inputs and an operator select
  2. calculate(a, op, b) throws for invalid numbers, unknown operator, divide by zero
  3. Button handler uses try / catch
  4. Show errors in red, results in green
  5. finally: log "calculation attempted"
Where this is used: Calculators, payment amount checks, any user-input processing.
calculator.htmlHTML
Module 17Practice Example 4 of 5

Unique Visitors with Set, Stock with Map

IntermediateAnalyse a day of shop visits: unique visitors with a Set and item stock with a Map.

Your tasks

  1. Visits array with repeated names
  2. new Set(visits) for unique visitors, .size for count
  3. A Map of item → stock
  4. sell(item, qty) updates the Map, throws if not enough
  5. Print the final stock with for...of over the Map
Where this is used: Analytics (unique users), inventory, caches.
set-map.jsJS
Module 17Practice Example 5 of 5

Global Error Catcher with a Friendly Banner

AdvancedProduction apps catch unexpected errors, show a friendly banner and log details for developers.

Your tasks

  1. window.addEventListener("error") and "unhandledrejection"
  2. Show a red banner "Something went wrong. Please refresh."
  3. Log the error message and time to the console
  4. Buttons that cause a TypeError and a rejected promise
  5. A Dismiss button hides the banner
HintReal companies send these reports to tools like Sentry so developers can fix bugs users hit.
Where this is used: Every production web app.
error-banner.htmlHTML
Module 17Module complete

Recap: What You Completed in Module 17

  • ✓Modern syntax: const, arrows, templates
  • ✓Spread (expand) and rest (collect)
  • ✓Object/array destructuring with defaults
  • ✓?. stops crashes; ?? gives defaults (keeps 0)
  • ✓Short object syntax, Map, Set, modern helpers
  • ✓try / catch / finally
  • ✓throw, built-in and custom errors
100%Module 17 done

Coming next

Part 4: Classes, OOP, modules, debugging, browser APIs and 5 capstone apps.

Quick quiz – click an answer

Q1. 0 ?? 10 gives:

?? only replaces null or undefined.

Q2. user?.address?.city when address is null gives:

Optional chaining stops safely.

Q3. Which block always runs?

finally runs whether or not an error happened.
PART 3 COMPLETE

Well done!

You have finished Part 3 of the Complete JavaScript Course.

Modules completed

  • Module 13: Timers, Dates & Animation
  • Module 14: localStorage: Apps That Remember
  • Module 15: Async JS: Callbacks, Promises, async/await
  • Module 16: Fetch & APIs
  • Module 17: Modern ES6+ & Error Handling

Keep all your practice files in D:\js-practice. You will reuse them in the capstone apps.

</> Code Lab
Edit the code – the preview updates as you type
Live preview