¢button ide"child™> Click Me \ | document. aetElementBuld( | grandparent’). addEventlistener('eclick',() => ¢ console. log( “Graniparent’ ); Ys document . getElementByld{ 'porent’) add&ventListener( ‘click’, Qs { console logl Parent”); +); document getElementById( ‘whi ld’) ;addEventitstenar( ‘click’, () => ( cansole, Log{ Child’); Ys -@: Bubbling can be stepped using event. stopPropagation( ). Dynamic Elements We can create, modify, and remove elements using JavaScript. Create Elements ~ 1 Apple const newltem = document; createElement(' Li’); 2 Banana néwltem,textContent = ‘Mango; newltem className * item’; 3 Cherry New item document. gotElementByld( ' List’). appendChild(newEtem) ; 7 Mango added! Modify Elements Remove Elements const item = document. querySelector{’ iter’); const item = document .querySelector(‘ item’); item textContent * "Updated Item’; if (item) | item-style.color = ‘green’ | item, remove{); itam.classList add( ‘active’ }; w } Useful Methods: createElement(), appendChild(), remove(), classList.add(), setAttribute(), etc. Practice Ideas Build a To-Do List (add, remove, mark as done)- Use event delegation for list item clicks. Create a FAQ accordion using event listeners. Highlight a menu item on hover using mouse events. Dynamically add and remove elements on button click, : - Promises i =e ie it ht in a nas ia mi i ed meee ie mee in ween ke a uae tee ie \ TOPICS j Ww .catch( ) ' (4) Creating Promises -Q: (2) .then() J) A Promise is an object thot represents the eventual -then() is called when a Promise is successfully fulfilled completion (or failure) of an asynchronous operation Tt receives the value passed to resolve(). and its resulting value. f — — const promise = new Promise((resolve, reject) => ( const promise = new Promise((resolve, reject) => { resolve("Data loaded successfully!"); let success = true; // change to false to see reject y; if Couccess) { promise. then( (value) => { resolve("Qperation completed successfully! #"); console.leg( "4 then() called:", value); } else { | | 1); reject("Something went wrong! XK"); 2 st Output ‘ : — —__——, | @ then() colled: Data loaded successfully! | | Key Points * Promise has 3 stotes: Pending, Fulfilled, Rejected | __ ee a es a »* resolve(value) —» moves to Fulfilled state = ‘nbait Ae ‘ ‘bakin \ a * reject(error) — moves to Rejectad state fers <4 iw —; yea ee -catch() ® finally() la -catch() {s called when a Promise is rejected. -finally() is called regardiess of whether the Promise is RS It receives the error (or reason) passed to reject(). fulfilled or rejected. Useful for cleanup code. ‘ R Promise t tect) => { | const promise = new Promise( (resolve, reject) => { const promise = new Promise({resolve, reject) = ‘ setTimeout(() => { reject(" X Failed to fetch data!"); resotve(""Request completed”); // try reject("Errar occurred” ) a }, 1902); promise Yi ; sthen( (value) => { promise emih. ue ry ethen tue) => console log( "This will NOT run”); = ee Suedeues®wakady }) .catch( (error) => { consele.tog("% Error: ", error); ») scatch( (error) => { console. tog(“A\ catch() catled:", error); 5 ) = — } — = —— = — | -finally(() => { Output | consale.log(" O finally() called: Cleanup done”); is = aA catch() called:: X Failed to fetch data! | | - Ms == — = ———— av = | @) Use: {feallij() 26) Kuda’: eeiderg: eldee ‘eonplectiona, | | ee veatch() handles errors and prevents your app from crashing, | | stop spinners, ete Chaining Promises @€ Real-Life Analogy Gide: Sameniry Each .then() returns o Promise, se chalk multiple actions ete ae “ iO ts SauuhanAledts ls thet Promise is like an online order fF Promise => 8 ste bi getitser * Pending -» Order ploced ; y | .then(user => getPosts(user.id)) «Ful
Success (Fulfilled) .then(posts => getComments(posts[@].id)) [J reject) + Failure (Rejected) * Rejected + Order failed -then( comments: => console. Log(comments)) Beast) =e Whaitdabtnenea a Pentti consale.log(“Error:", err) ) ; | * + -Finally(() => console.teg( “ALL done! ”)); HeabehG)) ee When jolted g -tatek() <9 Rans of ert = =—= ——S finally) > Either way, Tl Hacilly@)-s6 Rud eas + + WwW Keeps code clean and avoids “callback hell” si thank..you! = — > = —_ — ) CC a ee ee i i ee eM ee i ie i i ci ie mee Best Practices * Always handle errors with .catch(). * Use .finally() for. cleanup: tasks. * Return Promises in .then{) for proper chaining. © Keep each osuns function greet () { Key Points | console. log(“Fetching data...~); [ ] return “Hello, JavaSeript!"; . let data = await new Promise(resolve => ? } + asyne function setTimeout(() > resolve( "Data received!"), 2000) await can only be always returns | ): | : . 2 used inside on | a Promise. | qopanladaetiuta’, 5 | greet().then(value => console, log(value)); async function. | / Hello, JavaScript! ylescabee Ps o, JavaScript! f \ f : then() with | getData(); | LC oT ee a it. ee —— — a —_—__—_———~ Output (after 2 seconds) ae G2 Fetching dato... | | Data received! } * x Gi (3) Error Handling (4) Fetch API Basics aunt AL Use try...catch with async/await to handle errors The Fetch API is used to make network requests. when a Promise is rejected. Tt returns a Promise that resolves to the Response object. async function fetchUser() { Basic GET Request try { 3 ; = let response = owait fetech{ "httes) //api esenstaeeluaablithn| a, | cqxane: function: gebPostaC) € | if (Vewepbnee ok) \thvea amie (Erron( "User at found"); — ty ; | Let response « await fetch{ “htips://jsonplaceholder typicode com/posts"); let user = await response, jron{); try — code soasate.tog("User="| user); let posts = await response.jron(); // porse JSON dato if Cirasponse.ak) throw new Error ("Network reaponse was ant ok”); catch handle } catch (error) { ee console log(posts slice(Q, 3}); 1 first 3 poets | ronsole.tog(" X Error: *, error.messoge}; "= ) catch (error) ( | ) finally { finally always cansole.log("X Error”, error. message}; console, log(" J Done”); runs ) } } ) getPost=(); fetchser(); — — ee = = = = ~ HTTP. Methods ~ =) Possible Output | [Method _| Use Example 4 User: { id: 1, nome: “Alice” } GET Retrieve data fetch(urt) ||——= = —— = ian ——| op | | Post Send date fetch(url, { mathod: ‘POST’, body: data }) ee Ueerrinat Sev || PUT | Update data | fatch(url, { mathed: ‘PUT’, body: data }) —— ——— / DELETE Delete data fetch(urt, { mathod: ‘DELETE’ }) — a? et = —EEE————< = —_ ma mn; ' Async + Await vs Promises Quick Summary = | Using Promises Using Asyne/ Await . p Ine Declares tion that returns a Promise. Suan | aagne-funmeion banded w@ asy! > an async func ry then(ens <> res. json()) try { . . j mf ae Se ! Les haiaan) Lekb rma Hout: Paani ww await —» Pauses execution until a Promise is resoived. let data « t j | cotchlerr => console.loglerr)); cemealaagttotahe deons @ try..-cotch —» Handles errors ih asyne code. } catch (err) { ' Bi auger s console. log (err); a] finally — Runs code after try/catch, always. ‘ ¢ © Easier to read } : w Fetch API —+ Used to make HTTP requests. oi ic] Easier error hondling Always returns o Promise. S : 1 WY tond(); — L ee i) Best Practices | © Always handle errors with try.. catch. * Don't forget await with Promises. | | | | © Use async/await for better readability * Check response.ok before using response data. wv Bid Write async code. Handle errors. Build better apps! wv g Pa ToPrcs SSS SS ee ee ee ee ey eee eee eee @) try (2) catch The try block contains code that might cause an error The catch block hondles the error, It receives an error object Tf an error occurs, JavaScript looks for a catch block: with details about what went wrong ————a a == = t esult = riskyOperation(): | id r Error Object et result skyOp on(); OF Kade i ak let num = 16 / 0; a reset "try runs console. Log(result); first console-Log(num); @ name + Type | } catch (error) { & If errar } catch (error) { & message Details | console.log( "Something went wrong! "); catia is ‘ console.log(“Errar Neme:~, error.name); & stack + Where Jury | } catch. | console, Log(~Error Mestage:", error message); it happened & Program ‘doesn’t | console.Log(“Stack:", error. stack); Se | consele.log("Execution continues..."); wala ) | = | Output ae | Z Error Name: Infinity Pix Something went wrong! = a Gs Error Message: Division by zero Execution continues... a = | Stack: at Pri rE qeant console.Log{"User:", user); | function validateAge(age) { | rint fi flow uf (age < 18) ¢ = 2. Breakpoints throw new Error("Age must be 18 of above”); | When to Use: throw? © Pause’ code execution in DevTools Set breakpoints in Sources tab } | os to inspect variables. return “Access gronted!"; @ Invalid input . , ro | lel | ems issing data values of varinbles, Bee clyjects, «anit eepan: Console in DevTools try ( ney | | 4. Stack Trace console. Llog(validateAge(15)); | Violations | © Ny ; Look at error. stack in cote Cherak € & Critical fs: See the call stack in error teh NGeak ae a . ie failures messages to find the exact line. ss : console.log(“Validation Error”, error.message); —_—— a | \ >} xk 5. Use Strict Mode “use atrict"; (// at the jn = ~ Helps catch common mistakes. top of your file om A = ___ Sra Veiidnaiiee Eooes Age musik, he 4B See wv Browser Devloots (F12) ‘are your best friend! L _ } Use Console, Sources, Network & Application tabs. | Quick Summary | Common Built-in Errors | | Best Practices a try — Contains risky code 5 @ ReferenceError + Using undefined variable @ Write specific error messages [catch = > Handles‘ errors’ gracefully, Tire er ong tape efi swn | @ Don't ignore errors @ th =i i @ Syr a7 S: Tale @ Use try...catch around risky code throw janually create errors x) RangeError — Value out of range @ Log errors for better debugging. @ Debugging —* Find, inspect & fix issues. x) URIError — Malformed URI 7 @ Test error scenarios. | [ud | | Handle errors. Write reliable code [igi es wend Nhe error-aneenngecarefullyt | @ Keep your code clean and readable. | ~ Tk tells you exactly what went wrong. Don't fear errors, handle them like a pro! LY Catch. Fix. Improve. Repeat. wy (4) To-Do App (2) Weather App A simple To-Do application to: add, complete, delete Search any city to get current weather using the and filter tasks Data is saved in localStorage OpenWeatherMap API My Tasks i ae Eh —. Weather App = Kou JS (Exspeple) | 4h dd: Task async function getWaather{) { Adda naw dash Add addBtr.nddEventlistener(’click’, () => ( Euler ty nae const city * eltylnpat value trimt); const task = input, value -trim(): “ Of Uleity) return, | af (ltauk) return; — eonat ark + httpas/Yapl opetiiieithemarp. stg? All Active _ Completed tusks. push({ text: task, done: false }); dalu/Z. 5/Weather?q=Sfeity)Bunitsmuteiel input wolue + °"j Qpprid YOUR APT KEY"; tearn-dovaSerept w saveTosks(); New Delhi, IN ty ( randerTasket ); conat res = owait fetch{urt); (1) Build Projects Di: ®@ Clear Sky Uf Ulrds.ck) threw intw Erroet City not fount”); 47 Seve & Load : toast data + amit res jton{); CC) Practice Daily {iy | furetion saveTaskse) ¢ © Hiaentthae 30% showWeather (dat) locatStorage setItem( todos’, 32 C Wind: 12 kn/h JSON. strinalfy (tasks); Eels R ina a we } = like; 34°C errorMeg, textContent = err message; 2 tasks left Clear Completed function leadTasks() { | Updated: 10:30 AM ’ tasks = JSON porsa(locelStorage getTtem \ y (eedos YH 09°); a —— Bt — vy. Features 7 Features [A] Add, delete tasks (Filter: All / Active / Completed D Search city weather Handle errors (7 Mork as complete / incomplete 3) Notes App A notes application te create, edit, delete -and store notes in localStorage fH Data saved in localStorage B Show temperature, a Revision. Koy J5 (Example) fuurricdity, wird (Clean ond- responsive UL Let's revise the key concepts we learned in this 10-day journey: You are now re ——— t— 7 Core Concepts | BOM & Events Asyne JoyaScript | Junction addNote(titte, content? { = iS ] ‘My Notes Meating Ideas | eiak aan'-« | * Voriables, Dota Types . Select & Manipulate * Callbacks | | = (d-Dele- post). + Operators, Conditions * Event Listeners © Promises Discuss project roadmap tithe, content, + Loops © Event Bubbling © Asyne / ‘Await with: the team: ereatedAby new fetal). tolocaleStringl) + Functions & Scope * Event Delegation ° Fetch APE Meeting Idens Prepare demo My 55 © Arrays & Methods: * Dynamic Elements Ei Handi 10 May 2024 8 arn ; + ES6 Features yeaa ling scveoties( )} s rardenNates( ); JoveScript Concepts } Web § BestPaazices. OO ag 200 u function savalvtienl) am Aree: ___| ase rOeees. | LoeatStorage aatTtame ‘nates’, Project Plan J TSON. atringifyl tetas 2); “ Peeistiaie < Wes eee 0S May 2034 B y See 2 ees function \eodHotent) ( + JSON Methods * Debug. & test Phe totes + JSON parse((scalStorsgu. wetitem © Save User Data © Build real projects Unotes 2 11 120s | ) | —_ [le eatin What You Built (Y Create, adil, delete notes GY Show date & time To-Do App + Weather App + Notes App to build even bigger 2 1 Auto save witte wii 7 TF Simple & clean UL aide bathe applications! g | -Q- Project Ideas to Keep Building Exvanice: Tracker Blog Website & Monte: Search. Agp G2) Chat. Application ED E-Commerce UL QY Remember oP Next Steps You Did Tt! Practice daily. Build projects. Learn by doing. Keep coding and stay consistent | ths Learn frameworks (React, Vue, Angular) (Explore backend with Node. js (Build full-stack applications | & Code. Build. Debug. Repeat. That's how you become Congratulations on completing 10 Days of Intermediate JavaScript! Keep building, keep learning, keep growing! @ a great developer! cg le}