Partial preview of the text
Download JAVA SCRIPT PROGRAMMING IN 10 DAYS-ADVANCE and more Cheat Sheet Computer Programming in PDF only on Docsity!
» ADVANCED ~ avaScript <2 S10 DAYS) F< Learn. Build. Solve. Level Up! ee Classes © [DAY 24] - Object Oriented JavaScript | > foystrecters ¢ Encapsulation I> ° Polaron pita aaae 3 enn een Uy ¢ Browser Object Medel [DAY 22 22) - Advanced DOM & BOM « Timers ° Navigator Object CD fara DAL) - - API oe £..:} (DAY 24) ~ Advanced ES6+ Fy o (DAY 25] 25) = ~ ToS Modules EX DAY 26) - Mes & Performance DAY 23 27| - Advanced a Concepts 4|? [ DAY 30] - Final Advanced Projects Location Object REST APIs Fetching Data API Methods Handling pBespensee i eee8e Symbols Iterators Generators a! & Bie Leer & Expet Module Structure Code SEEN Call Stack Event Loop Garbage Collection Optonization alps iid AO) Promise Chaining Parallel Requests Promise . all () Promise. race ¢ ) coee#:?¢ ¢ Module Pattern DAY 28 28 5) - Dag Potterns ° Singleton Pattern | «@ Ds eek it cus © Hoistin (DAY 23 29 5) - ~ Jauaerigt I Interview Concepts e “f Hestng Revision © Execution Context e Die sa Chas Chat App Portfolio Website APL Dashboard ¢ Complete Revision —__— $Y Code Smart. Think Deep. Build Better. $4” —— OBJECT ORIENTED is a programming paradigm Object Oriented Programming based on the concept of «J! Ld "objects", which can contain data (properties) and code + A class is a blueprint (template) for creating objects. + Inheritance allows one class (child) to inherit + It defines properties and methods that the properties and methods from another class (parent). objects will have. * It promotes code reusability. * We use the ‘class’ keyword to declare a class. + Use ‘extends’ keyword to inherit oa class. mah A >) class Person { Key Points: w class Animal { Remember: a constructor(name) { constructor(name, age) { . 2 this.name * name; this.name = nome; // property * Class is just } * extends is used this.age * age; MW property a blueprint. speak() { to inherit. } return “S{this.name} makes a sound. ‘; + Objects are } + super() is used introduce() { f tiskannes } to call parent return “Hello, I'm {this.name} and écmatid' from class eonstractor. i *, class Dog extends Animal { Bog is child class i } Tom: ${th age) Geers hay); Hemme a class. constructor(name, breed) { super (name); “f coll porent constructor } «© Use ‘new’ this. breed = breed; : " “ keyword to } // Creating an object (instance) of Person class cant object, | speak() a ; const pl = new Person(‘Alice’, 20); // object return “${this.name} barks.”; // method overriding console. log (pi, introduce()); } // Hello, I'm Alice and I am 20 years: old. Ay const dogi = new Dog(" Buddy’, ‘Labrador’); console.Leg(dogi.speak()); // Buddy barks. X — {onsite Log (dog1. breed); ff Labrader 3 + A constructor is a special method inside a class: * Encapsulation means bundling data (properties) + Tt runs automatically when on object is created, and metheds together and restricting direct + It is used to initialize object properties. access to some data. Notes: Pat e Tt helps in dota hiding and security: class Car { } canes © Use ‘#° to create private properties (inside class). constructor(brand, model, year) { 3 construstot) (“class Account { ~ Note: a this. brand «= brand; t #balance; 4/ private property this model = model) TEE constructor(owner, balance) { » Private data this.year = year; once when this.owner = owner, cannot be accessed } the object is this. #bolance = balonce; ae id ceased. } irectly outside details() vv f TT } deposit (amount) { the class. return “${this-year} ${this.brand) ${this.model}’; | + It helps in if (amount > 0) this dtbalance += amount; ) setting initial } + Reems Sueur } Saline: getBalance() { methods (getters / const cad = new Gar(“Toyota';’ ‘Corolla’, 2024); } return this. ftbalance; // controlled access setters). consale.log(cari.details()); eats } ( j const ace = new Account {“Alice’, 1000); /f 2024 Teyoto. Coratla q , atc .deposit('500); ae console. log(ace.getBalance()); // 1500 ) C POLYMORPHISM f class Rectangle extends Shape { 4 Key Takea + Polymorphism means “many forms”. constructor(L, w) { super(); this.t = lt; this.w = w; } 2) wes? Ww « Different classes can have methods. with the same areal) { return this.t « this.w; } « Same method name name but different behavior. } ( ) but different o Tt is achieved through method overriding. ree = is achieved = pete eeriaing const ates ; implementation. lass Shape new Circle ‘ ‘i pater ra new: Rectangle(4, 6) + Depends on the return O; I object, not the , ) shapes. forEach(s #> console. log{s.orea())); reference. class Circle extends Shape { 1 Output: I 4 constructor(r) ( super(); this.r + r; } /} 78.5 aed ¥& area() { return 3.14 © this. « this.r; } Ht 24 K } - = HOW OOP WORKS TOGETHER "Class Constructor F-Object _ Methods " Inheritance " Encapsulation : Polymorphism ett, | —* [ (initializes) ] =e es ] —" ee | =| (reuse) |- [eae data) (Flexibility) ‘mle ly. lee nay ———-—-+=- — BENEFITS OF OOP —-——=-—------=-~---=-------- = Se, 'g Orgenined. Code v Mewsanitity v Ey Maintenance V Scalability Y Real-world Modeling v raesnnity - , Sees Seer eee eres esas eee eee eee SS > API INTEGRATION < faze (4) REST APIs * REST (Representational State Transfer) is an architectural style for building APIs. * It uses HTTP methods to perform operations on resources. © Resources are identified using URLs. HTTP. METHODS ) Method | Purpose | Example a GET j Retrieve data § GET /users POST - Create data | POST /users PUT Update data | PUT /users/1 L DELETE | Delete data DELETE lusers/\ | vw Most APIs return data in JSON format. JSON (JavaScript Object Notation) is easy to read and use in JavaScript. t} (3) API METHODS (with fetch) © GET — Retrieve data | fatch( https: //apt.example.com/items') © POST - Send data fetch( “https: //api.example.com/items’, { method: 'POST", headers: { ‘Content-Type’: ‘application/json’ }, body: JSON. stringify({ name: ‘Bock’, price: 500 }) }) © PUT - Update data fatch( “https: //api.example.cam/items/1', { method: ‘PUT’, headers: { ‘Content-Type’: ‘application/json' }, body: JSON.stringify({ name: ‘Notebook’, price: 300 }) }) © DELETE - Delete data fetch( "https; //api.example.com/items/1', { method: ‘DELETE’ }) wv Always check the API documentation randation for corres correct As endpoints and request formats, EXAMPLE: GET USERS FROM API APIs allow avtveal vcplleebions to talk to each other and exchange data. We: request a process it, and use it {reac —/ (2) FETCHING DATA e We use the fetch() function to make API requests. > e— Make request fetch( ‘https: //api.example.com/data' ) to the API -then(response => response. json()) -then(data => { <— Convert response console. log(data); to JSON }) <— Use the data .catch(error => { console.error(‘Error:' $23 YY _ J , error); <— Handle errors * Asyne / Await (modern way) asyne function getData(){ try { const response = await fetch( "https: //api.example.com/data’); const data = await response. json(); console. log(data); } catch (error) { console .error('Error:' , error); (4) HANDLING RESPONSES * A response has: Response Object status + status — success or error code (e.g., 200, 404) “statusText + statusText - message (e.g., OK, Not Found) —= —— = : enone + headers — additional info + body - actual data json() / text() « Check response status | fetch( "https: //api.example.com/data') -then(response => { if (tresponse-ok) { throw new Error('Network response was not ok’); "| <= Check iF status is ok (200-299) <— Stop if error | F Parse JSON « — ee response. json); iE xucoxes: | .then(data => console. tog(data)) vcatch{error => > console, error('Error:", error)); I Common status codes 200 201 400 401 | 404 500 es (Success) | Created Bad Request Unauthorized Not Found Server Error | \ ——$—$_— — _ / 2 ‘| a | (Tp: tp: | Use try...cateh with sopaiaonls for cleaner error handling. | a Ca, | eS — : How it works f — async function getUsers(){ 4. Request o> f BEST PRACTICES d try { i Send request 5 ov Always use HTTPS URLs. const response * await fetch( https: //jsonplaceholder.typicode.com/users’ ); to API if (lresponse.ok) throw new Error('Failed to fetch users’); v v Handle errors gracefully. const users © await response.json(); aR 5 Pe Check response.ok before users.forEach(user => { . APL aands bak => using data. | ee ee: ${user.name} — ${user.email}"); NFA — ay Keep APL keys secuees Sadak es i a i, of Read API documentation | console.error(‘Error:', error); | 3. Process carefully. { ‘ } Convert & use Use async/await for - iN getUsers(); \ fs ete } better “readability. Bx x 2 * —— — —— vy APIs connect your app to the world. Fetch it. Parse it. Power it! wv | _? = Y: Why ES6+? + Better data handling * Cleaner syntax > ADVANCED ES6+- ES6+ introduced powerful features that make JavaScript more efficient, flexible and fun! w + More control & flexibility * Modern JavaScript * A Symbol is a unique and immutable primitive value. + An iterator is an object that defines a sequence wy + Tt is often used as an object property key to nic shes: c& mmnth)) method: avoid name collisions. = next() returns an object { value, done }. * Created using Symbol(). + When done is true, the iteration is complete. Example with Array; oo id = Symbol(' id’); >} ; A Tora es const arr = [10, 20, 30]; : Alice! a Symbol( *id') const iterator = arrf{ Symbol. iterator ](); [id]: 101 creates a console. log(iterator.next()); // { value: 10, done: false } }; unique value console. log(iterator.next()); // { value: 20, done: false } le; b ° We ALi every time. console.log(iterator.next()); // { value: 30, done: false } ane Sear ta ~iy | console. Logliterator .next()); // 4 value: undefined, done: true } console. Log(user[i ; // 1014 console: log(Object:keys(user)); // [‘name'] Custom Iterator: /¢ Symbol properties ore not listed ( const range = { oo” * 1 in Object. keys() start: 4, “ashe L J end: 3, objects can be [Symbol . iterator )() { looped using let current « this.start; oncsak fy let Last = this end; hy Use Cases: return { - = k ¥ next() { Greching Ss age aise keys return current «<= Last { $ Hiding object properties ? { value: current++, done: False } for (let “ yf . * ‘ a . et num range * Defining well-known symbols in JS } + { done: true }; cintbestepaadl: Ww } Mi }oW4 23 = = Ee JW } J ) = jy / — (3) GENERATORS fe |(@ sets & mars | * Generators are special functions that can pouse and resume A. SETS execution using the yield keyword. | + They return a Generator object (an iterator). + Useful for handling asynchronous tasks and data streams: + A Set is a collection of unique values. } * No duplicates allowed, + Maintains insertion order. Example: “const set « jew SatCT4, 2, Z,.S23, MAY: BuAttione Bou) £ console. log(set); HW Set(4) { 1,2, 3, 4} yield’ 1; set.add(S); 4 add value yield 2; set.delete(2); // remove value yield 3; console. Loy{ set has(3)); V/ true | } _console.Llog(set size); “4 | const counter = count(); Mp _ console. log(counter.next()); // { value: 1, done: false } B. MAPS console. log(counter.next()); // { values 2, done: false } * A Map is a collection of key-value pairs. console. log(counter.next()); // { values 3, dane: false } + Keys can be of any data type. praca enna nn sy \_ console. tog(counter next()); // 4 welwe: undefined, done: true) | « Maintains ineertton’ order: Common (Methods Generator with for.-.of loop: const mapi'* aly Map); a | Set: add(), function* Letters() { ceeiSie ene ay er | delete(), hast), | ile ap.set(1, ‘One'); ' size, clear() } yield A’; . *' Nie i 1 ' yield 'B'; = are perfect for map.set(true, ‘Yes'); tt u yield 'C'; lazy evaluation console. log{map.get(‘name')); // Alice 1 "aap set(), ' } (generate values console. Log{map.get(1)); WW One get(), has(), | 3 0g{map.g for (let Letter of letters()) { on demand). console. log(map.has{ true)); W/ true delete(), } console.Llog(Letter); // A BC | map.deLete{ ‘name'); Jd remove key-value | | size, clear() (i | | console. Log(map. size); 7 2 4 (_ QUICK COMPARISON — \ [° ‘Feature | \What tits Key Benefit Example Use : KEY TAKEAWAYS | | Unique primitive | Avoids property Hidden object ; Symbols ails So ease Re ta vw Symbols create unique keys. Iter Object with next() Custom iteration Looping over Vv Iterators give you fine-grained cantrol over iteration. ators | method control custom data | Cusacaais | Rectang uth | Pause & resume Asyne flows, data | v Generators make async and lazy operations easier. ee) eee | siscation | streams 1) | pret, ‘a waiean aiSiciiedl Collection of No duplicates, Storing unique store ane aie ad me 5 unique values fast operations items | SoM Hore Veucval eerste Restle hea & . Key-value pair Any key type, Lookup tables, J fone ey “UPes | collection | ordered | caches J Ys Modern JavaScript is Powerful — Use — yy —_ ES6+ features to write Cleaner & Smarter Code! ¥y > MEMORY & PERFORMANCE < Why it matters? Improves speed & responsiveness Understanding how JavaScript uses memory and executes code helps us write faster, smoother and bug-free applications. Prevents memory leaks ut Better user experience >” Efficient resource usage : SS WW (7 Vf | (2) CALL STACK (2) EVENT LOOP * The Call Stack is a LIFO (Last In, First Out) data structure. * JavaScript is: single-thrended but con perform non-blecking + It keeps track of where we are in the program. operations using the Event Loop. - Wi a function is called, it is pushed on the stack. + It continuously checks the Coll Stack and the Callback Queue. 3° What ret ib isspappad off. + Tf the Call Stack is empty, it pushes the first callback from | the queue to the stack, How it works? ¥ Sts. sal y{ y) @ Globat Call Stack Callback Queue unction greet(name siecubion coated == Qusuas sayHeLLo( name) ; das:pudliod An: thescobenk: f™ __ {tak Soma) : (2) When a fi called = z unction . 2 function sayHello(name) { 4 ne salak creolint Evin oop calls 2 cansole,Log( ‘Hello ' + name); } (@) When the function returns, callback 3 its context is popped. — ale greet(' Alice’); a J ic) Rendict returns to the Howe isons? previous context. Stack Execution Flow @) A function is executed and pushed to Call Stack. ® When it makes an async call (e.g., setTimeout, fetch), ® ® ® i) the callback is sent to Callback Queue. sayHelle() @ When the Call Stack is empty, Event Loop pushes’ the Tor» Context greet() next callback to Call Stack. greet() | ops] Context fore Eavgls: Output: vor > Global Global Bisa Glebel consote.log(' Start’); 1. Start Cite Ln rg Context Context setTimeout(() => console.log('Timeout'), 0); 2. End console, Log('End'); 3. Timeout = Ce ish to, oe > oe oe | te Tf the stack size exceeds the limit, we get: | S(ay- Even with a delay of Ons, setTimeout runs loter because | RangeError: Maximum call stack size exceeded ! ‘@ dine: -calbbveck is placed tthe queue, net the- stack: ' PN Se ee eee —_ si = (@ GARBAGE COLLECTION * JavaScript has automatic memory management yia Garbage Collector (GC). + It frees up memory by removing objects that are no longer reachable. * This helps: prevent memory leaks. How it works? The GC looks for “unreachable” objects (no references to them) and removes. them. Reachable (Kept in memery) (Gasol (Garbage Collected) ‘ cS ry ao oO ®& a Common causes of memory leaks: * Global variables (unintentionally created) + Unused event listeners + Closures holding onte large objects + DOM elements not removed properly ‘(@) OPTIMIZATION TIPS : Avyouly = var data > [); vw —— — Seahaie function oat() ¢ data push(1); } They stay in memory for entire , shige Batters function sat() 1 lifetime of the app. tonst date = (3; | tt Use let / : date, push( 1); Block~scoped variables ore cleaned — up after the block is done. F — _— | HW Bad 425 , : . for (Let 4 = 0) 4 < 100; Lee) ¢ | % Minimize DOM Manipulations decument body iene oe “ep eie’etps’; DOM operations are expensive. } Batch them and update once. H Good let Atel « “* for (let ¢ = 0; & < 100; toe) { htm o= “spoteceted p's ) document body. innearHTML » html: const map = new Map()) | By Use Efficient Data Structures mop-set('id', osonerd; map.get("id'); /7 O(1) Use Map/Set for faster lockups. Funetian init) { tonst btn = document getElemantByld( *btn'); const handler = () + console. tog(" Lich"); btn addEventListener( click’, hander); {1 kekee when not Wedded btn. removeEvantLlistener('click', handler); aT | | We Remove Unused Listeners Clean up listeners to avoid leaks. | Fe Lozy Load & Code Split eed only ESA te kadai 7+ Dynamic. import (code splitting) const module © = LN _ ——— ——— = SUMMARY CHEAT SHEET | CALL STACK | EVENT LOOP GARBAGE COLLECTION PERFORMANCE + LIFO structure + Enables asyne behavior = + Frees memory automatically + Write efficient code + Trocks function calls 1” 6 tise Call Sine » Callback Qua N01 + Removes unreachable objects (> gy’) « Optimize resources eens nga | 7 ins hen stack is ply Y + Helps: prevent memory Leaks + Better performance & UX Too many calls--+ Stack overflow owoit import(’ /module js”); || — } wv Write less. Do more. Optimize today for a faster tomorrow! eg > ADVANCED ASYNC CONCEPTS < (72... * Improve performance Mastering JavaScript’s asynchronous power * Non-blocking operations = to write faster, cleaner and more reliable code. CR Se es (@ PROMISE CHAINING “| (@® PARALLEL REQUESTS * Promise chaining is the process of executing multiple When tasks are independent, run them in parallel to save time. asynchronous operations one after another, Don't wait for one to finish before starting the next, * The result of one promise is passed to the next. © TF any prantee ts: cejected, donteal Jungs to ..cubcht?) Example: Fetch user, posts ond albums ot the same time. + c ( fetchUser(1) const userPromise = fetch('/api/user/1'). then(res => res. json()); sthen(user => { const postsPromise »* fetch('/api/posts').then(res => res. json()); console. log('User:’, user); const albumsPromise = fetch('/api/albums').then{res => res. json()); return fetchPosts(user.id); // return next promise | Fach .then() i ») returns a -then(posts => { ‘sss oom Using Promise.all() to wait for all to complete; console. log(‘Posts:', posts); a return fetchComments(posts[0]. id); so we can Promise. all([userPromise, postsPromise, albumsPromise]) ] }) chain them! -then(([user, posts, albums]) => [{ -then(comments => { console-log(user, posts, albums); console. log{ *“Comments:*, comments); 3) tae us § L -catch(err => console error('Error:', err)); console error('Error:', error); | 9: | Why Parallel? Flow: WY Faster: total time = time of a Gegeiet. 2 Si _— the slowest request | Fetchuser() | — | fetchPosts() | => | FetchComments() | —> | Request 2] _ —- Y Efficient use of network & Ln Tees: | Gescentes Request 3 a | si \ WZ Better performance for | FY Always return a promise in ithen() to keep the chain going, | Sie: ugey fot | oe nt ac ' |W One .catch() at the end can handle all errors in the chain. | [Tete Sie ss ectiness Sena Set (Se eS Se SS eM =i fz —\a . ns ——_* (3) PROMISE. ALL() (4) PROMISE. RACE () * Waits for ALL promises to resolve. * Waits for the FIRST promise to settle (resolve or reject). + Resolves with an array of all results Cin the same order). « Resolves or rejects as soon as the first promise completes. + IF ony promise rejects, it rejects immediately. pat Syntax yntax: Promise. all(iterable) | | |_ Promise rose(iterable) Example: Example: a 7 = > const timeout = naw Promise((_. reject) => | setTimeout(() => reject( “Request timed eut’), 3000) Promise all (LE fetch’ /opi/user’).then(res => res. jzon()), | | | fetch(“/opi/posts"),then(res => res json()), » Ffetch(‘fapi/albums‘). then(res <> res. json()}) | const request = fetch('/api/data') then(res => res. json()); ) -then({{user, posts, albums]) => { Promise race([request, timeout]) consale.log( ‘ALL data:', { user, posts, albums }); .then(data ©> console, log('Data:', data)) ») ) eatch(ere => console.errer('Errar:', err)); -enteh(err => console error(‘Failed:', ere)); - ‘ . 7 Key Points Use Cases oints havior Implement timeouts Key - e -—>—----- » Returns a single promise * sin © Returns a single promise, F | Sr Get first successful | © Resoligs thn vray promise in the ‘terse vessles. | AL 7 > resolves with ll values: + Settles as: soon as the first promise settles. response from * Rejects as snon ax one promise rejects: Any 3 + rejects immediately. | * Useful for timeouts, fallbacks, and fast responses. multiple sources | « Maintains the order of results lee ae || tr Fallback strategies —— ——— =—— =p ist = == —_ = = = = COMPARISON | 4 Feature Promise Chaining Parallel Requests Promise all() Promise. race() oY Use async/await for better 7 a | — es —= ——— = readability. Purpose ——»—Run teks one after ninother | Run independent tasks together Wait for all promises to Finish Wait for the first promise to settle VW Handle errors using try/eatch ———S _ — T — = CPT. or -catch(). Behavior Sequential Concurrent (parallel) Rasolues: winée ott essai Re pe-relorte: sehen @ Ran tasks in porallel when | | Rejects if any rejects one settles they are independent. Value possed from Y Use Promise allSettled() when Pill: | Ceamernnget Sermon i pull agile Abra AE all scwaale pe ee || gfe: Rasik ‘all iruaulia, an’ 2 = i + some fail. |, Use Case — Dependent operations Independent operations Need all results Need fastest result / timeout = | VY Avoid lunaséessary ‘async — = = = =“ | | __ operations, J Async code is all about performance and user experience. Next Level: oe Un the righ tl fr te right jb! PS [Ur | El Why These Matter? ‘ 7 -_ — — _ — ¥ Builds strong JS fundamentals Core concepts every JavaScript developer must know vv sa a a ae to write better code and crack any interview! Y > r = @ HOISTING (2) CLOSURES REVISION * Hoisting is JovaScript's default behavior of maving + A closure is a function that remembers the variables declorations to the top of their scope before code execution, from its lexical scope even when the outer function . Only declarations are hoisted, not initializations. has finished execution. * Variables declared with var are initialized with undefined, + Closures are created every time a function is created, * let and const are hoisted but not initialized (TDZ). at function creation time. Example: . Very useful for data privacy, currying, callbacks, ete L . How it works (Memory Phase) E le: console tog tens df undefined efor Enaaiike r How Cl Work var a = 10; : function outer(x) { outer(5) creat , er creates consele.leg(b); // ReferenceError Global Execution Context let count = 0; : exesuibion: contesd let b = 20; ar wut Puree return function inner() { | count++; consele.leg(c); // ReferanceError let b cuninitialized> console.log( ${x} —» ${count}”); outer Lexical Environment const « = 30; _- a ea } const ¢ ; x= § ; | t= 3 ascent AC eboekst sayHello | function def. sail unction sayHello() { (hoisted) console-log( ‘Hello’ ); [ J const fr = outer (5); t } J fat); #4 5 > 1 inner() = 5 ~ fr(}; ¢/ 5 —> 2 (remembering outer's Key Points fit); v2 5 -» 3 variables) W Function declarations are fully hoisted. — ~ HY vor is initialized with undefined. Key Points Be let ond const are in Temporal Dead Zone (TDZ) Yr Closures give a function access to its outer scope variables. until their declaration is encountered. Fr Variables in closures live in memory as long as the closure exists. J sd Helps in maintaining state between function calls. _ Wf; 7 @ EXECUTION CONTEXT (4) SCOPE CHAIN Execution Context is an environment in which JavaScript code * Scope Chain is the mechanism JavaScript uses to resolve variable is evaluated and executed. references. = Every time a function runs, a new Execution Context is created. * When JS looks for a variable, it searches in the current scope. * There are 3 types of Execution Contexts: | Tf not found, it goes to the outer (parent) scope. This continues 1. Global Execution Context (GEC) until it reaches the global scope. 2. Function Execution Context (FEC) « Tf still not found, ReferenceError is thrown. 3. Eval Execution Context Example: ; Anatomy of Execution Context fede Fateh: “or ‘Bxecution: (Cont 7} i ; inner() Scope — mie function outer() { (iigsy gerne +, 4, Variable Environment ut Variables, Functions, Arguments let b = ‘outer’; LS : Order | 2. Lexical Environment // Scape info tee Scope Chain) function tnnet ©) f outer() Scope ie inner() a | | | 3, this // Nolue of ‘this’ keyword ol bet © = “inner”; Cb} ' ' F < console. log{a); // global ae 5 2s outer() Scope | | Execution Flow 7 console -log(b); 7} outer L 12 Global Scope \ | Global EC Function EC 2. (nested console Log(e); // inner Global Se ' | terested A) aan Sey fears — | Function ECs) } vo loa ; is called) inner (); —T Seats } Exacution Context Stack (Call Stack) J ds —~—_} [ (LIFO - Lost In First Out) ] — wat Kee) Key. Points | Keay Pettis VW JS ts single-threaded. Executes one command ot o time. Sipe Diet 0 SR GE CRI, Retatate ine CE: AGL ES, | W Execution Context is created in two phases: Memory Phase & Code Phase. | | vt Tt affects variable resolution, not variable lifetime. Ye Contexts ore pushed to Call Stack and popped when execution completes. WW Lexical Scope = Scope defined by where variables and functions J are written in the cade. (_ QUICK COMPARISON \ ¥ "INTERVIEW TIPS i Concept What it is | Key Takeaway | iiss ma jplndiions. to Declarations: hoisted, v Explain with diagrams. L. Zs | Sop ehissegpe |_Raibietteabione ne: __ w Use simple code examples. Clo Function remembers older | Enables data privacy & SUres scope: .variebles stabs. persistence wW Talk about real-world use cases. , Environment where code Has 3 parts & lives in wf Mention e cases and gotchas. Entcation Content |” ei ok “ge 3° <== chess oF Soe — Fat ae vy Practice writing outputs on paper. Scope Chain 4 5 | for variable resolution outer te global $F Understand deeply. Code clearly. Think like a developer. Ace the interview! TY = FINAL ADVANCED PROJECTS = Apply everything you learned. Code. Debug. Optimize. Deploy. You've got this! a What You'll Gain Vv Real-world experience ¥ Strong portfolio projects v Problem solving skills Build real-world projects. Vv Interview confidence C fQ aC) a A real-time chat application with rooms, users A modarn, responsive portfolio’ website to showcase and instant messaging. - = your skills and projects. 3 a % Roce fees = in . MyPortfolio Home About Stilts Projects. Contact “8 Key Features mn a ‘Alice 4020 aM Key Sections ee : Hello ! . * User nuthentication (Sign up / Login) | random ona * Home / Hero Hi, I'm Developer * Create / Join chat rooms # help Seb: 2314 * About Me , £ % Hi Alice! Haw’s it goina? © Kile | build fast, responsive © Recltime. westaging SA seoaine and modern web apps. * Onting users list Online Users eucd Ly © Projects * Typing indicators @ Alice * Experience View My Work Alice 90.22 aM gion oink toed @ Bob Shall we build somethiig t Recimnesiels ® Charlie amazing today? 42° * Contact Me * Dark’ Mode Toggle Featured Projects | Type a message > L =) Chat App Weather App Todo App Tech Stack Real-time chat Get real-time Manage your application weather into daily Tasks @ S| Us @) 3) ex 6 Live Damo + Live Dama + Live Demo = css JavaScript Socket.IO Noda. js Express MongoDB Tech Stack + Mini Code (Real-time Message) @ 15 a S a = HTML ¢ss JavaScript AOS / GSAP ff clinnt M. server sacket.amit('sendMessage’, { reom, message )); | socket.on("seiviMessuge’, (dota) «> { Mint Codie: (Theme Toggle) qT | socket on{ racoiveMassage , (date) =» { | fo te(data room) emit{ receiveMessage’, { ee — lips ------—--- | | anpendMessage( data); tart Nectet. inerrant. ( sonst toggle = document .getElementByldt * thameToggte*); | w Keep it cleon i | Ys | mmarsagee dete, medsngs, conat bady = document body; | Make it responsive | time: Date.nowt) | u 2 | | js toggle. addEventlistenerf' click’, () => { ‘ Saas | | Hs | body classList. toggle( dark"); iv Show your projects | r —-— — = toggle-textContent » body.clasalist.contains(' dark’) he Be itt @ Bonus! Add @mojis, file sharing, message notifications. »: a Neca OS ma oS — —<—== a, © Pt DASHBOARD gpl @ COMPLETE REVISION A dashboard to visualize data from public APIs Revisit all important concepts and strengthen with charts and filters. = ata ©) your fi : Key Feabu “g 7 Users Orders Reverie Vinaa What to Revise * Fetch data from API 1,245 568 $12,430 8,920 4 Dili patie TWN thon risa TAIN wv Variables; Data Types & Operators Control Functions * Charts & Graphs Usern Over Time, Top Countries v. te ry 8 * Filters & Search 1m oa vi Arrays & Objects = Paginaki = ® wa vy DOM & BOM + Dark Mode Be) pes vo ES6+ Features ° : © ter V Asynchronous JavaSeript Tach Stack Oya “Rese Ree ee Se J vo Advanced Concepts (Closures, Hoisting, ete) g S| as (as) ® v Design Patterns KK Vo Error Handling. & Debugging JoveSenipt Chart js Fetch API Y Perfo ec & Optimization Mins Code (Fetch & Renda ‘ ; finn le { r) APIs: You Can Use vo Projects & Best Practices Fateh{ “https: //jeonptavehuldar. typicode. com/usars’) ithentrns <> cae, jnon()) * TSGNPlacchalder ——— then{data +» { s ‘ = tonat tabla = document .getElemantByfd(” uierTable”); teicher Revision Checklist aohigeeicar-Stiee 2 a GF Understand the concept Review Notes A tr> $ {userid} 4u> | $ fuser, name} | ~ eR P ; std ${user, email } ’; + GitHub API © :Reneticn: with ial test's a ° Rak & Apr 1 ER RanA ein: praia & Explain to others | -catehferr => eanaoleerror(err))) ! BH Solve problems & Stay Consistent! PY Bonus: Add authentication, CSV export, and more charts a ; = | 30-DAY JOURNEY SUMMARY FINAL TIPS ¥ Keep building projects = oa” 6 6S, You're Ready! i Rik Bese aie Arrays, Objects, Asyne, Patterns, Game Build, Learn, Confident. Skilled ¥ Stay curious | ahi Pow DOM, BOM Performance Grow Job Reads! v¥ Never stop learning + id ul J You did it! a w Congratulations on completing 30 days of JavaScript! Keep building. Keep growing. 377 wy