Download JAVA SCRIPT PROGRAMMING IN 10 DAYS-INTERMEDIATE and more Cheat Sheet Computer Programming in PDF only on Docsity!
] @ Callbacks | Async & Await @ Synchronous vs Asynchronous @ setTimeout e setInterval ® async © await ® Error Handling @ Fetch API Basics Error Handling e try © catch e throw ¢ Debugging Techniques Keep Practicing. Keep Building. Become a Better Developer ! — rm rr eee ae - [os 1k Advanced Functions Re Array Advanced. Methods Callback Functions ® map() © Higher Order Functions f @ filter() [ 4.2, 3.4 © Closures —— © reduce() 7 T N TY ———= e find() @ Function Expressions rz, ® @0 20 | L ane e forEach() fi 7) fr wee ES6 Features rece DOM Advanced © Spread Operator © Event Listeners © Rest Parameters ® Event Bubbling © Default Parameters © vert Dilation © Modules ® Optional Chaining ® Dynamic Elements \% = = = = == Creating Promises .then() .catch( ) fi tnally( ) Gaaal Storage © Local Storage e Session Storage | | © JSON Methods |, © Save User Data | BOD Intermediate Project e To-Do App | © Weather App —= | e Notes App 7 © Revision for these topics * Intermediate JavaScript (10 Days) _ ida Day 11 — Advanced Functions ‘TOPICS ) LF Callback Functions w Higher Order Functions $Y Closures $Y Function Expressions (4) Callback Functions (2) Higher Order Functions A callback function is a function passed as an argument to another function, which is executed later. function greet(mame, callback) { console. log( "Hello, callback{); // calling the callback } | "* name # “O")5 | function sayBye() { console. log( "Goodbye! £5"); “Y } Output greet("Alice", sayBye); Hello, Alice! Goodbye! | | Real-world Example Used in: Event handling, API calls, setTimeout, | reading files, etc. Closures A closure is a function that remembers the variables from its outer (enclosing) scope even ofter the outer function has finished executing. | function outer({) { | let count = 9; } // private variable return function inner() { A higher order function is a function that either: e takes one or more functions as arguments, or « returns a function. Example: map() const numbers fty: 25 33-4]; | numbers.map(function(n) { const squares return n * n; })5 console.log(squares); // [1, 4, 9, 16] | | Common HOFs in JavaScript e map() — transforms each item e filter() —> filters items * reduce() —> reduces to a single value — performs an action on each item | @ forEach() Faclie: Gypsesnaas A function expression is a way of defining a function by assigning it to a variable. | const add = function(a, b) { return a + b; | 33 | consote.leg(add(5, 3)); // 8 Named Function Expression | const greet = function sayHi() { | console. log( “Hill"); I! } * Has a name (sayHi) | « Useful for recursion ond debugging | Practice Ideas (oy Write a function that accepts a callback and runs it after 2 seconds. Use map(), filter() and reduce() on an array. Create a counter using closure. count++; ee Named vs Anonymous console.log{ “Count: ", count); a = } Why Useful? | Anonymous Function | } : const greet = function() { cours “ == | conanbas bagiHEl"Y; const counter = outer(); data privacy and | i counter(); // Count: 1 maintaining state. 1 = counter (); // Count: 2 * No name after ‘function’ counter (); // Count: 3 | * Used once, reference via variable = ———— L - als, 7 i a oo Foe os = *@ — Quick Summary | | (@ Callback Functions —> Pass functions as arguments and execute later, 5 [Higher Order Functions —> Operate on functions (take or return functions), | | Closures —> Remember outer scope variables even after the outer function ends. = | (Function Expressions —> Define functions using expressions, store in variables: ® \ — Se — ~ t& & t Understand Functions Deeply. Write Better Convert function declarations to expressions. Spread Operator Expands an iterable (array, string, object) into individual elements. iy gu = e 47 With Arrays Gy 4 const arri = [1, 2, 3]; os: const arr2 = [.. .ored, 4,°5); // [1, 2, 3, 4, 5] Use Cases const arr3 = [0, ,..arr1, 4]; // [0, 1, 2, 3, 4] © Copying arrays/ 1 With Objacts objects const obj1 = { a: 1, b: 2 };
acc + n, 0); } console.log(sum(1, 2, 3)); console.log(sum(5, 10, 15, 20)); function userInfo(name, ... console, Log{ Name: console. log( "Skills: } userInfo( ‘Alice’, ['3s', // Skills: // 6 ff 50 skills) { ${name}"); ', skills); 'yS!, "HTML", 'HTML", "CSS'); 'eSss"] G3) Default Parameters Allows setting default values for function parameters: 4 | function greet (name = ‘Guest’, message = ‘Hellot') { | Modules (ES6 Modules) reusing it, console. log('${message}, ${name}!' ); } greet(); // Hello!, Guest! greet( Alice’); // Hello!, Alicet greet('Alice', 'Hi');, // HL, ‘Alice! a) Why? |} | Makes functions | flexible ond | reduces the need for multiple | function overloading. 6) Optional Chaining Safely occesses deeply nasted properties without throwing. an error if an intermediate value is null or undefined. f const user = { name: ‘Bob’, address: { city: “New York’ } yi console, log(user.address, city); // New York console, Log(user.profile?. age); // undefined (no errar) console. log(user? .address?. city) ; 7/4 New York | console. log(user?.settings?.theme?.coler); // undefined i ww Spread Operator —> Expands elements of arrays/objects, (Rest Parameters — > Collects remaining arguments into an array. 1 cay Default Parameters —> Sats default values for parameters | (Modules —> Organize code in separate files and reuse. | | AH Optional Chaining — > 7 @ math.js (module file) export const add = (a, b) => a + b; | return a - b; export const multiply = (a, b) => a * b; export default function subtract(a, b) { | last parameter, | * Gathers the | rest into an | Modules help in organizing code’ into separate files and * Use. ‘export’ iedherw aol ‘import’ to use. * Use export default’ for a single default export per file, | Why Use It? ¥ Avoids “Cannot read < property of undefined” Access nested properties safely, Wy Mi ! Practice Ideas * | | Without Optional Chaining YY (user 8& user address £8 } } user address, city) { console. Log(usur. address. city); alse { console.log( "Not. available’); Merge two arrays using spread operator. Create a function that accepts any number of numbers and returns their average (use rest + reduce). Set a defoult theme in a function Create and import your own module. Safely access user data from an API response using optional chaining. app.is (using the module) import subtract, ( add, multiply } from”. /math.js"s console: log(add(2, 3)); console. Log(multiply(2, 3)); | consote.Log(subteact(5, 3)); 7s 6 “2 Comparison With Optional. Chaining console-log(user?. address? city 7? ‘Nat available”); // Shorter, cleaner, 1 /¢ and sofer! Learn. Practice, Build. Repeat. @ You've Got This! Po ey) Event listeners allow us to run code when an event happens on an element. // Select an element const btn = document. getElementByld( ‘myB8tn'); // Add event Listener btn addEventListener({ ‘click’, function () { eonsole.log('Button clicked!" ); »; // With arrow function btn-addEventListener( 'mouseover", () => { btn. style. backgroundColor = ‘Lightblue'; 5 Common Events | bods 8 Baa click dbiclick mouseover mouseout keydown submit change | @: Use addEventlistener() instead of inline events (onclick). | @) Event Delegation Instead of adding event listeners to many child elements, we add one listener to their parent and use the event target. HTML How it works sul id="List™> 1. Click on any Apples/LO 2. Event bubbles up to - Bananas/Li> |
- Cheerye/L> & WE Gia: seer Sarat | 4. Take action based on the target
const List * document. getElementByld(” list’); List addEventListener{ elick’, funetion (e) { if (e.target,tagtome =*= ‘LE') { console logl' You clicked:', #. target. textContent); | | e,target-style-coler = ‘crimson’; | ) | )): eae Quick seers (@ Event Listeners Listen for events and run code. @ Event Bubbling Events bubble up from child to parent. Event Delegation @ nner Elements we Pro Tip —> Use sonctirefal 0%, wll sbocoms Keep bad DOM = clean ans Cal code orgprizes! =" Handle events at parent level using evant target. Create, update, and remove elements with JS. (2) Event Bubbling When an event happens on an element, it first runs on that element and then “bubbles up” to its parent elements. HTML Structure nd ¢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}