{"id":28522060,"url":"https://github.com/swathireddy369/javascript-execution-flow","last_synced_at":"2025-07-04T00:31:11.933Z","repository":{"id":290592973,"uuid":"974229683","full_name":"swathireddy369/javascript-execution-flow","owner":"swathireddy369","description":"Exploring the execution flow of JavaScript through small programs focused on functions, scopes, memory, and core language behavior.","archived":false,"fork":false,"pushed_at":"2025-05-20T15:45:19.000Z","size":164,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-06-09T08:49:50.412Z","etag":null,"topics":["execution-context","hoisting","lexical-env","scope-chain","shortest-jjs-program","temporal-dead-zone","undefinedvsnotdefined"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/swathireddy369.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-04-28T13:03:03.000Z","updated_at":"2025-05-20T15:45:23.000Z","dependencies_parsed_at":"2025-05-15T18:40:11.662Z","dependency_job_id":null,"html_url":"https://github.com/swathireddy369/javascript-execution-flow","commit_stats":null,"previous_names":["swathireddy369/javascript-execution-flow"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/swathireddy369/javascript-execution-flow","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/swathireddy369%2Fjavascript-execution-flow","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/swathireddy369%2Fjavascript-execution-flow/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/swathireddy369%2Fjavascript-execution-flow/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/swathireddy369%2Fjavascript-execution-flow/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/swathireddy369","download_url":"https://codeload.github.com/swathireddy369/javascript-execution-flow/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/swathireddy369%2Fjavascript-execution-flow/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":263426040,"owners_count":23464791,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["execution-context","hoisting","lexical-env","scope-chain","shortest-jjs-program","temporal-dead-zone","undefinedvsnotdefined"],"created_at":"2025-06-09T08:42:42.569Z","updated_at":"2025-07-04T00:31:11.895Z","avatar_url":"https://github.com/swathireddy369.png","language":"JavaScript","readme":"# javascript-execution-flow\nExploring the execution flow of JavaScript through small programs focused on functions, scopes, memory, and core language behavior.\n# JavaScript Execution Flow Programs\n\nThis repository contains a collection of small JavaScript programs created to explore and understand the internal execution flow of JavaScript.  \nThe focus is on mastering how JavaScript handles functions, scopes, memory allocation, hoisting, closures, and basic operations at a deeper level.\n\n## 📚 Topics Covered\n- Function Declarations and Expressions\n- Execution Context and Call Stack\n- Variable Scope (Global, Function, Block)\n- Hoisting Behavior\n- Closures and Lexical Environment\n- Primitive vs Reference Types\n- Memory Management Concepts\n- Asynchronous Execution Basics (setTimeout, Promises)\n\n## 🎯 Purpose\n- Build a strong foundational understanding of how JavaScript works under the hood.\n- Visualize and trace execution contexts, scopes, and memory behavior.\n- Prepare for technical interviews by deeply understanding language mechanics.\n- Improve ability to debug and write optimized, clean JavaScript code.\n\n## 🛠 Repository Organization\n- Each program focuses on a single concept or behavior.\n- Clear comments are included to explain step-by-step execution.\n- Folder structure categorizes programs by JavaScript feature.\n\nExample Structure:\n DAY - 1:\n//execution context \n//hoisting variable and function\n//functions working and variable scope\n DAY - 2:\n//shortest javascript program\n//this === window\n DAY - 3:\n//undefined(allocated memory at GEC ) and notdefined (not allocated any memory yet)\n//loosely type(any type of data can be assigned)\n//lexical environment \n//scope chain\n//TemporalDeadZone (it is belongs to let and const hoisting)\n🔹 Execution Context\nThe environment in which JavaScript code is evaluated and executed.\n\n🔹 Hoisting\nVariables and functions are hoisted.\n\nvar, let, and const are hoisted, but only var is initialized with undefined.\n\nTemporal Dead Zone (TDZ) applies to let and const.\n\n🔹 Temporal Dead Zone (TDZ)\nTDZ is the time between hoisting and initialization for let and const.\n\nAccessing let or const before initialization → ReferenceError.\n\nUnlike var, which is hoisted and initialized with undefined, let and const are not initialized until the interpreter evaluates their definition.\n\n\nconsole.log(a); // ReferenceError\nconsole.log(b); // undefined (due to var hoisting)\n\nlet a = 9;\nvar b = 9;\n🔹 Reference Errors vs Syntax Errors vs Type Errors\n📌 ReferenceError:\nTrying to access a variable that is:\n\nNot defined (for var)\n\nIn TDZ (for let and const)\n\n📌 SyntaxError:\n\nlet a = 10;\nlet a = 10; // ❌ Redeclaration with let\n\nlet a = 10;\nvar a = 9;  // ❌ Conflict with let\n\nconst a;    // ❌ Must initialize const\n📌 TypeError:\n\nconst a = 10;\na = 9;      // ❌ Cannot assign new value to const\n🔹 Shortest JavaScript Program\nAn empty file is a valid JS program.\n\n🔹 Functions and Variable Scope\n\nFunctions create their own scope.\n\nVariables defined inside functions are not accessible outside.\n\n🔹 this === window\nIn the global context (non-strict mode), this refers to the window object.\n\n🔹 undefined vs not-defined\nundefined: memory allocated but not initialized.\n\nnot-defined: not allocated any memory yet.\n\n🔹 Loosely Typed Language\nJS allows variables to hold values of any type dynamically.\n\n🔹 Lexical Environment\nThe structure that holds identifier-variable mapping.\n\nIncludes the variable object and reference to the parent lexical environment.\n\n🔹 Scope Chain\nEach lexical environment has a reference to its outer environment.\n\nEnables variable access up the chain.\n\n🔸 Example: Block Scope \u0026 Variable Declarations\n\nvar b = 9;  // global scope\nlet a = 8;  // script scope\n\n{\n   let a = 10;    // block scope\n   var b = 20;    // still global scope\n   const c = 30;  // block scope\n   console.log(a); // 10\n   console.log(b); // 20\n   console.log(c); // 30\n}\n\nconsole.log(a); // 8 (from script)\nconsole.log(b); // 20 (var is globally updated)\nconsole.log(c); // ReferenceError (c is block-scoped)\n\n🔹 Scope\nScope defines where you can access a particular variable or function:\n\nGlobal Scope\n\nScript Scope\n\nBlock Scope\n\nFunction Scope\n\n\n\n\n\nDay-4:\n\n## 🔒 JavaScript Closures\n\n### 📘 What is a Closure?\n\n- A closure defines a combination of a function with its lexical environment bundled together.\n- When a function is returned, it returns with its lexical environment (i.e., it remembers its lexical scope).\n- It does not hold values directly — it holds a **reference** to the lexical scope.\n\n---\n\n### 🔁 Example: Unexpected Behavior with `var`\n\n```javascript\nfor (var i = 0; i \u003c= 5; i++) {\n    setTimeout(function sample() {\n        console.log(\"var\", i);\n    }, 1000);\n}\nIt prints 6 six times.\n\nJavaScript does not wait for setTimeout to complete; the loop finishes first.\n\nClosures formed here hold a reference to the same variable i.\n\n✅ Solution: Use let to Fix the Above Issue\njavascript\n\nfor (let i = 0; i \u003c= 5; i++) {\n    setTimeout(function sample() {\n        console.log(\"let\", i);\n    }, 1000);\n}\nlet is block-scoped.\n\nA new copy of i is created in each iteration, and the closure remembers its own reference.\n\n✅ Another Solution: Use Function Wrapper with var\njavascript\n\nfor (var i = 0; i \u003c= 5; i++) {\n    function X(i) {\n        setTimeout(function sample() {\n            console.log(\"var with function args\", i);\n        }, 1000);\n    }\n    X(i);\n}\nA new scope is created inside X(i) function.\n\nClosure holds reference to the local copy of i.\n\n🧠 Closure Behavior in Lexical Scope\nEach function in JavaScript has access to its parent lexical environment.\n\nEven if the function is executed outside its original scope, it remembers where it was created.\n\n\n\nfunction outer() {\n    var outer = 10;\n    function inner() {\n        console.log(outer); // lexical outer env\n    }\n    return inner;\n}\nouter()();\nouter() returns the inner function.\n\nouter()() executes the returned inner().\n\n\n\nfunction outer(b) {\n    function inner() {\n        console.log(outer, b); // lexical outer env\n    }\n    var outer = 10;\n    return inner;\n}\nouter(\"hello\")();\ninner() forms a closure and remembers b and the outer scope.\n\n⚠️ Memory Considerations\nClosures may lead to over-consumption of memory.\n\nVariables captured in closures are not garbage collected until the closure is destroyed.\n\nCan lead to memory leaks if not managed properly.\n\n🧹 Garbage Collection and Closures\nGarbage Collector: A program in JavaScript engines that frees up space for unused variables.\n\n\n\nfunction a() {\n    var a = 9, z = 8;\n    return function b() {\n        console.log(a);\n    }\n}\na()();\nClosure is formed with a only because z is unused and gets garbage collected.\n\nAccessing a works, but accessing z throws a ReferenceError.\n\nDay-5:\n//function statement and function declaration as well\nfunction xyz(){\n    console.log(\"hii\"); \n}\n\n//function expression\n// assigning function as a value to the variable\n\nvar a=function (){\n       console.log(\"hii\"); \n}\n\n//anonymous function \n//a function which does not contain any name\nfunction (){ //identifier exepcted\n\n}\n//but we can use anonymous functions in function expression\n\n//Named function Expression\n//  nothing usually we use anonymous function in function expressions but if we define name to it then it considered as named function expression\n\nvar b=function xyz(){\n    console.log(\"hello\");\n    console.log(xyz); //here it does not throw any error as it is already had an entry in local scope of xyz\n    \n}\nconsole.log(b);\nconsole.log(xyz); //as xyz has no entry in the global execution context it throws reference error as it is not defined\n\n\n//difference between [arameters and arguments\n\n// the function where we define and give names in the paranthesis are called as parameters (idetifiers,labels)\n// but from where we call that particular a\\function and passing values to the parameters which we have defined while function declaration is knowmn as arguments(values) \n\n\nfunction c( name, age){//these are parametrs\nconsole.log(name,age);\n\n}\nc(\"swathi\",\"27\");//these are arguments\n\n\n// First class functions\n//first class citizens\n// it's ability to treated as a vlue and passed as argument and return from function\n\nfunction y(x){\nconsole.log(x);\nreturn x;//it can aslo return a function \n}\n\ny(function (){//it logs the anonymous function which we have passed\n\n})\ny(function z(){//ity logs the named function which we have passed\n\n})\n\n\n\n\ndocument.getElementById(\"clickMe\").addEventListener(\"click\",function (){ //call back function\nconsole.log(\"button clicked\");\n});\n//whenever event happens then only this call back function enters into call stack\n\n\n//closures demo with event listners\nlet count=0;\ndocument.getElementById(\"clickMe\").addEventListener(\"click\",function (){ //call back function\n    console.log(\"button clicked\",count++);\n    });//here we are using gloabl variable its is not good practise\n\n\n    // create closure \n\n  function attacheventListner(){\n    let count=0;\ndocument.getElementById(\"clickMe\").addEventListener(\"click\",function (){ //call back function\n    console.log(\"button clicked\",count++);\n    });//here we are using gloabl variable its is not good practise\n    }\n    attacheventListner();\n\n    // it forms a clouse with count \n\n\n    //scope demo with event listeners\n\n    // event listener have same scope as clouse has\n\n    //Garbage collection for event handlers\n\n    // event listeners are too heavy because they use memory after the event happend should be garbage collected but we dont know who is going to trigger the event again so one of the considering disadavnatge of event listeners\n\n\n\n    Day 6:\n    event loop and call back queue\n\n    here as we are using settimeout,fetch,localstorage,console.log and document.get all these are not javascript things \n    although these all are browser things okay in our javascript we have functions so to execute those function in browser we have javascript engine inside we have call stack so js engine just execute the function which are in stack as soon as they enter into it ,now comes into topic so in this nature js doesnot wait for any other yhings to execite in functions which are in stack as it is single thread and syncronous but if we need some timer ,fetch and log kind of behaviour browser provides web api's to access these settime and fetch all those browery things to access in our js by using global window ,as it is global mention window.console.log or window.settimout does not explicityly required .whenever w use console.log in our js code it simply call wiindow.console api to get access to the console panel in browser and our message which we provided dispaly in that pannel i got suprised i have been using console.log without knowing this stuff. \n    this is fine\n    what if we have to use settimeout and fetch in our js then lets see about set timeout whenevr we see settimout in our code which we executing currenlty the it simple call window.fecth then it simple register call backa nd attach timer to it in webapi's and js engne continues its work as i mentioned earlier js does not wait for anything to execute okay after my call stack is being empty then event loop always monitor whetehr call stack is empty or not and whether call back conatins anything to execute.\n    here once the register call brower timer as soon as expired then it direclty pused to call back queue now event loop get to know one cb is inside call back queue then if event loop ckecing if call stack becomes empty the is pull out the cb from callback queue and push it to call stack this is the way our call back executes.then coming to fecth  it is not like call back queue little difference is there.whenevr our js engine encpounter any fetch call it simply call window.fecth api like timout but once window .fecth api calls it regitert he promise in web api's and once the promise gets resolved then it got pushed into microtask queue observer not callback queue its microtaskqueue\n\n\n\n    callback pusehd to callbackqueue\n    but fecth,mutationobserver things pusehed to microtaskqueue and microtaskqueue has high prioty than call back queue so as soon as event loop got to know somehonh is waiting in the mircostaskqueue as priority cincers it first pulled out the microtask qeeu adn pusehd into call stack queue as soon as it becoems empty once the microtaskqueuebecome empty then only event loop will take care of call backqueue\n\n    here we have mutation observer see it also enter into the microtaskqueue like promises here it observes that any dom content changes if happend it also pused to micortask queue as iyt high priority than call back\n\n\n    here we have a concept called starvation : the call back queeu tasks being delayed by having microtask piled up recursively \n\n\n    JavaScript Event Loop and Asynchronous Operations\nCall stack, Web APIs, callback queue, and microtask queue work together to handle JavaScript execution:\n\nJavaScript Engine:\n\nHas a call stack to execute functions\nSingle-threaded and synchronous\nExecutes code immediately without waiting\n\n\nBrowser Web APIs:\n\nNot part of JavaScript but accessible via global window object\nExamples: setTimeout, fetch, localStorage, console.log, document.getElementById\nDon't need explicit window. prefix (it's implied)\n\n\nCallback Queue (Task Queue):\n\nContains callbacks from timers and I/O operations\nLower priority than microtask queue\nExamples: setTimeout, setInterval callbacks\n\n\nMicrotask Queue:\n\nHigher priority than callback queue\nContains promises and mutation observers\nExamples: fetch (Promise), MutationObserver\n\n\nEvent Loop:\n\nMonitors call stack and queues\nWhen call stack is empty:\n\nFirst checks microtask queue and moves tasks to call stack\nOnly after microtask queue is empty, checks callback queue\n\n\n\n\nExecution Process:\n\nsetTimeout: Register callback in Web API → timer expires → callback queue → call stack\nfetch: Register promise in Web API → resolved → microtask queue → call stack\n\n\nStarvation:\n\nCallback queue tasks get delayed by recursive microtasks\nHigher priority microtasks continuously push new microtasks\nCallbacks in the task queue never get processed\n\nhttps://claude.ai/public/artifacts/e25c5b19-4008-49ad-a06d-b270ca025c7b\nhttps://claude.ai/public/artifacts/06ea46e6-c1da-47fb-a185-99498e5ef92c\n\nJava script engine:\n\nto execute piece of js code we need javascript runtime environ ment it contains js engine,web api,microtaskqueue,call back queue and event loop so here broswer has JRe and nodejs has JRE where the some api are same together but some are different right.\n\nhere lets come to js engine\n\nevery brower has different js engines it's not a machine it just piece of code written in c++ \nit has been executed by our brower.\n\nthe process includes \n\njs code-parsing(generate tokens - AST((ast exploer)(abstarct syntax tree))- interpreter +compilation \nearlier did not have compiler for javascript it direclty execute the code later versions has jit compiler it make code efficient as much as it can(here are some techniques inlining,copy elusion,inline caching) and convert it into bytecode althought execution and compilaion done paralley \nif we use interpreter it's fast whereas compiler give efficiency\nthe execution can be done using memory heap and call stack as we know call stack well and come to memory heap it allocats memory to the functions and variables which are in callstack and once execution is done and if there any unused var or function found just do garbage colletion by mark sweep algo and the very famous js engine is V8 chrome one it has iginite interpret and turbo fan compiler and mark and sweep orinaooc garbage colletor lets go to v8 blog and explore more on it \n\nas we have processureal ,functional and object oriented languages here java script can do all of these lets explore more it does all these\n\n\n\n\nJavaScript Runtime Environment\nJavaScript Runtime Environment (JRE)\n\nRequired to execute JavaScript code\nContains: JS Engine, Web APIs, Microtask Queue, Callback Queue, Event Loop\nDifferent environments: Browsers and Node.js have their own JREs\n\nSome APIs are common between them\nSome APIs are environment-specific\n\n\n\nJavaScript Engine\n\nNot a machine but code written in C++\nExecuted by browsers\nEach browser has its own JS engine\nFamous example: V8 (Chrome, Node.js)\n\nJavaScript Processing Flow\n\nParsing:\n\nGenerates tokens\nCreates AST (Abstract Syntax Tree)\nTool: AST Explorer\n\n\nExecution:\n\nEarlier versions: Only interpreter\nModern versions: JIT (Just-In-Time) Compiler\nExecution and compilation happen in parallel\nInterpreter: Fast startup\nCompiler: Better efficiency\n\n\nOptimization Techniques:\n\nInlining\nCopy elision\nInline caching\n\n\nExecution Environment:\n\nMemory Heap: Allocates memory to functions and variables\nCall Stack: Execution context\n\n\nGarbage Collection:\n\nMark and Sweep algorithm\nCleans unused variables and functions\n\n\n\nV8 Engine Components\n\nIgnition: Interpreter\nTurboFan: Compiler\nOrinoco: Garbage collector\n\nJavaScript Programming Paradigms\n\nProcedural\nFunctional\nObject-oriented\n\n\n\nASP Exploer.net\nv8\nmarker sweep\nEcmascript\n\n\nV8:\n\nv8 is the javascript engine which is developed by google chrome and written in c++(google engineers) and it uses in the  platforms like chrome and node.js\n \njavascript source code-\u003e parser \u0026 AST Generator -\u003e then \nInterpretor(iginition) lightweight interpretor executes the code quickyl before that conver it into bytecode to execute quickly but not as much as machinecode.\n\nturbofan (JIT compiler) it monitors frequenclty used code \nit optimizes and   compiles byte code to efficient machinecode \n\nGarbage collector: do memory management by efficient garbage collection system for unused var and functions eg: mark-sweeper,mark-compact,scavanger \n\noptimizations: inline caching,hidden calsses\n\n\nV8 Processing Pipeline\n1. JavaScript Source Code\n\nStarting point: Raw JavaScript code\n\n2. Parser \u0026 AST Generator\n\nParses JavaScript source code\nCreates Abstract Syntax Tree (AST)\n\n3. Interpreter (Ignition)\n\nLightweight interpreter\nConverts code to bytecode\nExecutes code quickly (but not as fast as machine code)\n\n4. JIT Compiler (TurboFan)\n\nMonitors frequently used code\nOptimizes and compiles bytecode to efficient machine code\n\n5. Garbage Collector\n\nHandles memory management\nRemoves unused variables and functions\nImplements efficient collection systems:\n\nMark-sweep\nMark-compact\nScavenger\n\n\n\nKey Optimizations\n\nInline caching\nHidden classes (for organization)\n\nhttps://claude.ai/public/artifacts/fd52059d-e388-40de-abf2-317a00114bc7\n\nDay 7:\n\nconcurrency model:\ntrust settimeout issues:\nas the part of setting up the environment so use live server to run our small website or the things which we are running in our index.html i came to know that witout body or head tag we can not initilaize live server wow amazing i was amazed\n\nas i understand concurrency means it s ability to a system to manage multiple tasks without blocking each other,they do not do necciserly simoultaniously but they manage effecltivly without blocking each other, like a eaxmple a chef boiling water and put aside meanwhile chopping vegetables here he is not doing the tasks at same time managing effiecenlty -----interleaving them on availability and readyness\n\nmanaging multiple tasks at same time\n\n\n\nhere if we put setTimeout(function cb(){},0) even the timer set for 0ms still it regietrd as call back in web api's environment and it will be pushed to call stack through event loop only when the call stack becomes empty\n\nhere javascript is single syncronous and fast execution beciase of we cannot block main thread execution for call backs or any other thing event loop should wait until call stack becmoes execute lets say we have code to execute time for 10ms after that 10ms execution and call stack became empoty then only our 0times cb will be pused to call stack\n\n\n\nJavaScript Concurrency Model Notes\nCore Concepts\n\nConcurrency: System's ability to manage multiple tasks without blocking each other\n\nTasks don't run simultaneously but are interleaved efficiently\nExample: Chef boiling water while chopping vegetables (managing tasks efficiently)\n\n\n\nJavaScript's Single-Threaded Nature\n\nJavaScript is single-threaded and synchronous in execution\nOnly one operation runs at a time on the main thread\nCannot block main thread execution for callbacks\n\nEnvironment Setup\n\nLive server requires proper HTML structure (body/head tags) to initialize\nMust include basic HTML structure in index.html\n\nsetTimeout Behavior\n\nEven with setTimeout(function cb(){}, 0):\n\nThe callback is registered in Web APIs environment\nTimer is set (even if 0ms)\nCallback is pushed to callback queue\nEvent loop waits until call stack becomes empty\nOnly then is the callback pushed to call stack\n\n\n\nExecution Order\n\nIf main code takes 10ms to execute:\n\nThe 10ms code runs completely\nCall stack becomes empty\nOnly then will the 0ms callback be pushed to call stack via event loop\n\n\n\nWhy This Matters\n\nUnderstanding this model helps explain why asynchronous operations don't block execution\nEven \"immediate\" timeouts (0ms) must wait for current execution to complete\nJavaScript maintains its single-threaded nature while appearing to handle multiple tasks\n\n\nhttps://claude.ai/public/artifacts/f51e6545-3e8d-4bcc-801c-5a385bbb493e\n\n\n\nHigher order function:\n\na functions takes function as paramter and return function and the function  which has been passed through this highe rorder function is known as call back\nconst radius=[3,1,2,4];\n\nconst calculateArea=function (radius){\n    const output=[];\n    for(let i=0;i\u003cradius.length;i++){\n        output.push(Math.PI * radius[i] *radius[i]);\n    }\n    return output;\n}\nconsole.log(calculateArea(radius));\n\nconst curcumference=function(radius){\n    const output=[];\n    for(let i=0;i\u003cradius.length;i++){\n        output.push(2 * Math.PI * radius[i] );\n    }\n    return output;\n}\nconsole.log(curcumference(radius));\n\nconst daimeter=function(radius){\n    const output=[];\n    for(let i=0;i\u003cradius.length;i++){\n        output.push(2 *  radius[i] );\n    }\n    return output;\n}\nconsole.log(daimeter(radius));\n\nconst radius=[3,1,2,4];\nfunction area(r){\nreturn Math.PI*r*r;\n}\nfunction circumference(r){\n    return Math.PI*r;\n}\nfunction daimeter(r){\n    return 2*r;\n}\nfunction calculate(radius,logic){ //higher order function //and here all the function which are passed as paramater to this function bemocome scall backs\n    let output=[];\n   for(let i=0;i\u003cradius.length;i++){\n       output.push(logic(radius[i]));\n   }\n   return output;\n}\nconsole.log(calculate(radius,area));\nconsole.log(calculate(radius,circumference));\nconsole.log(calculate(radius,daimeter));\n\n\n\nconsole.log(\"============================prototype=======================\");\n\n\n\nArray.prototype.calculate1 = function(logic){ //higher order function //and here all the function which are passed as paramater to this function bemocome scall backs\n    let output=[];\n   for(let i=0;i\u003cthis.length;i++){\n       output.push(logic(this[i]));\n   }\n   return output;\n}\nconsole.log(\"map\",radius.map(area));// i was amazed with this i do not know it works like this before but i was using map  just map the element and remaining this would done my own \n// to achieve map behaviour by using our function calculate lets make changes\nconsole.log(\"proptotypE\",radius.calculate1(area));\nconsole.log(\"proptotypE\",radius.calculate1(circumference));\nconsole.log(\"proptotypE\",radius.calculate1(daimeter));\n\nArray.prototype in JavaScript\nArray.prototype is the foundation of JavaScript arrays, containing all the built-in methods and properties that every array can access. Here's what you need to know:\nCore Concept\nWhen you create any array in JavaScript, it inherits methods and properties from the Array.prototype object through JavaScript's prototype chain. This is what allows you to use methods like map(), filter(), and push() on any array.\njavascriptconst numbers = [1, 2, 3];\nnumbers.map(x =\u003e x * 2); // [2, 4, 6]\nKey Array.prototype Methods\nArray methods fall into three main categories:\n1. Iteration Methods (Non-mutating)\n\nforEach() - Executes a function for each element\nmap() - Creates a new array with results of calling a function\nfilter() - Creates a new array with elements that pass a test\nreduce() - Reduces array to single value (accumulator pattern)\nsome() - Tests if at least one element passes a test\nevery() - Tests if all elements pass a test\n\n2. Mutation Methods (Modify original array)\n\npush() / pop() - Add/remove from end\nshift() / unshift() - Remove/add from beginning\nsplice() - Change contents by removing/replacing elements\nsort() - Sorts elements\nreverse() - Reverses order of elements\n\n3. Access Methods (Non-mutating)\n\nslice() - Returns shallow copy of portion of array\nconcat() - Joins arrays and returns new array\njoin() - Joins elements into string\nindexOf() / lastIndexOf() - Find element positions\nincludes() - Checks if array includes element\nflat() / flatMap() - Flatten nested arrays\n\nExtending Array.prototype\nYou can add custom methods to all arrays by extending Array.prototype:\njavascriptArray.prototype.myCustomMethod = function() {\n  return this.map(item =\u003e item * 2);\n};\n\n[1, 2, 3].myCustomMethod(); // [2, 4, 6]\nHowever, this practice is generally discouraged in production code as it can lead to conflicts and unexpected behavior.\nBest Practices\n\nLeverage existing array methods instead of writing custom loops\nUse non-mutating methods when you want to preserve original data\nAvoid extending Array.prototype directly in production code\nUnderstand which methods mutate the original array and which don't\n\nThe included diagram illustrates how Array.prototype connects to the Array constructor and individual array instances, plus the major method categories available on all arrays.\n\nhttps://claude.ai/public/artifacts/29027752-4a20-451f-a5a0-743050848a4b\n\n\n\n1.first class function: the ability to treat function as variable and pass function as argument it return the function and assign that return value to varibale is first calss function\n\n\n2.higher order functions: a function that allows function as argument and return function\n\n3.call back function a function that passed trhough argument fir another function\n\n\nhere call back function passed as argument to huigher order function its abiloity is called first class function\n\n\nDay-8:\n\n// Sample array\nlet arr = [5, 1, 3, 6, 2];\n\n// ========================== MAP ==========================\nconsole.log(\"================= MAP =================\");\n// MAP: Creates a new array by applying a function to each element\n\n// Method 1: Named function declaration outside map\nfunction double(i) {\n    return i * 2;\n}\nconsole.log(\"Double:\", arr.map(double));\n\n// Method 2: Anonymous function inside map\nconsole.log(\"Triple:\", arr.map(function(i) {\n    return i * 3;\n}));\n\n// Method 3: Arrow function (most concise)\nconsole.log(\"Binary:\", arr.map(i =\u003e i.toString(2)));\n\n\n// ========================== FILTER ==========================\nconsole.log(\"\\n================= FILTER =================\");\n// FILTER: Creates a new array with elements that pass a test\n\n// Method 1: Named function declaration\nfunction isOdd(i) {\n    return i % 2; // Non-zero values are truthy (odd numbers)\n}\nconsole.log(\"Odd numbers:\", arr.filter(isOdd));\n\n// Method 2: Anonymous function\nconsole.log(\"Even numbers:\", arr.filter(function(i) {\n    return i % 2 === 0;\n}));\n\n// Method 3: Arrow function\nconsole.log(\"Odd numbers (arrow):\", arr.filter(i =\u003e i % 2 !== 0));\n\n\n// ========================== REDUCE ==========================\nconsole.log(\"\\n================= REDUCE =================\");\n// REDUCE: Accumulates array values into a single result\n\n// Method 1: Named function declaration\nfunction sum(acc, curr) {\n    acc += curr;\n    return acc;\n}\nconsole.log(\"Sum:\", arr.reduce(sum, 0));\n\n// Method 2: Anonymous function\nconsole.log(\"Sum (anonymous):\", arr.reduce(function(acc, curr) {\n    acc += curr;\n    return acc;\n}, 0));\n\n// Method 3: Finding maximum value\nconsole.log(\"Max value:\", arr.reduce(function(acc, curr) {\n    if (acc \u003c curr) {\n        acc = curr;\n    }\n    return acc;\n}, 0));\n\n// Method 4: Max with arrow function\nconsole.log(\"Max (arrow):\", arr.reduce((acc, curr) =\u003e {\n    if (acc \u003c curr) {\n        acc = curr;\n    }\n    return acc;\n}, 0));\n\n\n// ========================== PRACTICAL EXAMPLES ==========================\nconsole.log(\"\\n================= PRACTICAL EXAMPLES =================\");\n\n// Array of objects\nlet people = [\n    {first: \"Swathi\", lastName: \"Amaravadi\", age: \"27\"}, \n    {first: \"Rajesh\", lastName: \"Kodakandla\", age: \"33\"}, \n    {first: \"Gopireddy\", lastName: \"Amaravadi\", age: \"25\"}, \n    {first: \"Anand\", lastName: \"Yannamaneni\", age: \"27\"}\n];\n\n// Example 1: Map - Create full names array\nlet fullNames = people.map(person =\u003e person.first + \" \" + person.lastName);\nconsole.log(\"Full names:\", fullNames);\n\n// Example 2: Reduce - Count occurrences of each age\nlet ageFrequency = people.reduce((acc, curr) =\u003e {\n    if (acc[curr.age]) {\n        acc[curr.age]++;\n    } else {\n        acc[curr.age] = 1;\n    }\n    return acc;\n}, {});\nconsole.log(\"Age frequency:\", ageFrequency);\n\n// Example 3: Chaining methods - Get lastNames of people over 30\nlet over30LastNames = people\n    .filter(person =\u003e person.age \u003e 30)\n    .map(person =\u003e person.lastName);\nconsole.log(\"LastNames of people over 30:\", over30LastNames);\n\n// Example 4: Alternative using reduce for the same operation\nlet over30LastNamesAlt = people.reduce((acc, curr) =\u003e {\n    if (curr.age \u003e 30) {\n        acc.push(curr.lastName);\n    }\n    return acc;\n}, []);\nconsole.log(\"LastNames of people over 30 (with reduce):\", over30LastNamesAlt);\n\n\nhttps://claude.ai/public/artifacts/864c8182-bd9e-4d29-827a-2e21653dbf10\n\n\n\n\n================================\nWeek -3\n\nDay -9\n\ncallbacks: importance of callbacks\nasyncronous behaviour exist in javascript only because of callbacks although every feature has its own white and black side so here as we coverd white face of callbacks as asynronous nature in javascript however black face would be \n1)callbackhell:\n\ncalling one callback inside another function and one more call back inside that callback this chaining is defined as callback hell\n\n2)inversion control: as we passing our callback to another function then we are missing control of that callback function althpugh it has been controlled by function which it has been passed through\n\n\nAsynchronous behavior exists in JavaScript only because of callbacks.\n\nAlthough every feature has its own white and black side, here we covered the white side of callbacks — that is, the asynchronous nature in JavaScript.\n\nHowever, the black side would be:\n\n1) Callback Hell\nCalling one callback inside another function, and then one more callback inside that — this chaining is what we call callback hell.\n\n2) Inversion of Control\nWhen we pass our callback to another function, we lose control over that callback. It’s now managed by the function we passed it to.\nhttps://claude.ai/public/artifacts/7361e1d4-755e-4cf5-9c0b-32e5573ced9e\n\n\nTopic 2:\nWhat is a Promise?\nA Promise is an object which represents eventual completion or failure of an asynchronous operation.\n\nPurpose of Promise:\nAs we discussed earlier, we have the black side of callback usage in our JavaScript applications. Those are:\n\nCallback Hell\n\nInversion of Control\n\nTo resolve those issues, we need Promises.\n\nInversion of Control:\nHere, we are giving control of our function to another function by passing it as a callback.\nSo in that case, we are not aware of what’s happening behind the scenes — it may call our callback twice or may skip it, depending on the code of the function we passed our callback to.\n\nExample of Inversion of Control:\n\n\norderPlace(cart, function redirectToPayment(orderId) {\n    console.log(\"payment\");\n});\n// here we lost our control on the function which we are passing through another\n// this is defined as inversion of control\n// so to avoid that we use:\n\nconst promis = orderPlace();\npromis.then(function redirectToPayment() {\n    console.log(\"payment\")\n});\nTo gain trust, we just call our API function — it gives us a Promise (which has 3 states: pending, resolved, rejected).\n\nFind the above definition for Promise.\nThe structure of a Promise object:\n\njavascript\nCopy\nEdit\n{\n  prototype: Promise,\n  state: fulfilled (or pending, rejected),\n  result: data\n}\nOnce we get the Promise, we attach a callback function to it using .then().\nIt will be called only when the Promise has been resolved — this way we achieve trust over the callbacks.\n\nNow inversion of control is resolved.\nBut we still have one more main issue: callback hell.\n\nTo resolve that, we use Promise chaining.\nIn callback hell (pyramid of doom – very ugly and hard to maintain), we pass one callback into another repeatedly.\nSo it grows horizontally.\n\nExample of Callback Hell:\n\njavascript\nCopy\nEdit\norderPlace(cart, function (orderId) {\n    redirectToPayment(orderId, function (paymentId) {\n        orderSummary(paymentId, function (summary) {\n            console.log(\"summary\");\n        });\n    });\n});\nTo avoid that, we use Promise chaining — in one Promise, we pass another function.\nOnce the Promise is resolved, it calls our callback automatically and repeatedly.\n\nPromise chaining example:\n\njavascript\nCopy\nEdit\nconst promise = orderPlace();\n\npromise.then(function (orderId) {\n    return redirectToPayment(orderId);\n}).then(function (paymentId) {\n    return orderSummary(paymentId);\n});\nOr another way:\n\njavascript\nCopy\nEdit\nconst promises = orderPlace()\n    .then(function (orderId) {\n        return redirectToPayment(orderId);\n    })\n    .then(function (paymentId) {\n        return orderSummary(paymentId);\n    });\nTo use one Promise’s result in another, we should return the result from the .then() block.\n\nTo represent callbacks in Promise chaining, instead of anonymous functions, we can use arrow functions as well — it’s up to the developer’s decision.\n\nNow it does not grow horizontally but follows a vertical, readable order.\n\nhttps://claude.ai/public/artifacts/077cb0df-d099-42db-b0b0-8942b66f3ebc\n\n\n\nDay-10:\n\n// Create a new promise using the Promise constructor.\n// It takes a callback function as an argument, which has two parameters: resolve and reject — these are given by JS.\n\n// Based on the scenario, the promise will either be resolved or rejected.\n// If resolved, we simply return: resolve(value);\n// If rejected, we throw an error using: reject(new Error(\"error message\"));\n\n// All the above part is related to the producer of the promise.\n\n// Now coming to the consumer part:\n// When we are receiving a promise, we can attach a callback function to handle the resolved value\n// and a failure callback function to handle rejected cases — using .then and .catch respectively.\n\n// To handle a resolved promise, we use:\n// promise.then() — here we receive the resolved value, and if we want to use that value in the next step, we should return it from this callback.\n\n// To handle errors, we use .catch():\n// It catches any error thrown in the promise chain above it.\n// If we want to continue processing even after a rejection, we can place .catch() just below that promise.\n// Once the error is handled, the rest of the steps will continue their work.\n\n# Making Sense of JavaScript Promises 🔄\n\nHere's my notes on how Promises work in JavaScript:\n\n## The Basics of Promises:\n\n### Producer Side:\n- Create a new promise using the Promise constructor\n- It takes a callback with two parameters: resolve and reject (given by JS)\n- Based on the scenario, promise either resolves or rejects\n- If resolved: `resolve(value)`\n- If rejected: `reject(new Error(\"error message\"))`\n\n### Consumer Side:\n- When receiving a promise, attach callbacks with `.then` and `.catch`\n- For resolved promises: `promise.then()` - we get the resolved value\n- To use that value in next step, return it from this callback\n- For errors: `.catch()` catches any error thrown in promise chain above it\n- If we want to continue even after a rejection, place `.catch()` right below\n- Once error is handled, rest of steps continue working\n\n## Real Example - Shopping Cart Flow:\n\n```javascript\nconst cart = [\"Kurta\", \"shoes\", \"watch\", \"bag\"];\n\n// Version 1: Promise Chain with Complete Syntax\nconst promise = createOrder(cart);\npromise.then(function(cartId) {\n    console.log(\"createOrder\", cartId);\n    return proceedToPayment(cartId);\n}).catch(function(err) {\n    console.log(\"error\", err); // handle reject\n}).then(function(paymentInfo) {\n    console.log(\"proceedToPayment\", paymentInfo);\n    return orderSummary(paymentInfo);\n}).then(function(summmaryId) {\n    console.log(\"orderSummary\", summmaryId);\n    updateWallet(summmaryId);\n}).catch(function(err) {\n    console.log(\"error\", err); // handle reject\n});\n\n// Version 2: Cleaner Way\ncreateOrder(cart)\n  .then((cartId) =\u003e proceedToPayment(cartId))\n  .then((paymentInfo) =\u003e orderSummary(paymentInfo))\n  .then((summmaryId) =\u003e updateWallet(summmaryId))\n  .catch((err) =\u003e console.log(\"error\", err)) // handle reject\n```\n\nThis avoids promise hell (similar to callback hell) where code grows horizontally and becomes hard to read.\n\nEach function (createOrder, proceedToPayment, etc.) returns its own promise, making the chain work properly.\n\n#JavaScript #WebDevelopment #Promises #AsyncProgramming\n\n\nhttps://claude.ai/public/artifacts/07a61b9b-fa25-4cd2-a017-c568b8d48479\n\n\nPromise types:\n# JavaScript Promise Combinators Explained\n\nHere's my notes on the 4 types of Promise combinators in JavaScript:\n\n## 1) Promise.all()\n- Waits for all promises to be settled\n- Success case: Returns array of all resolved values when ALL promises resolve\n- Failure case: Rejects IMMEDIATELY when ANY promise rejects\n- Returns the error of the first rejected promise\n- Example:\n```javascript\nPromise.all([p1, p2, p3])\n  .then((value) =\u003e console.log(\"Promise.all\", value))\n  .catch((err) =\u003e console.log(err))\n```\n\n## 2) Promise.allSettled()\n- Similar to Promise.all() but handles failures differently\n- Waits for ALL promises to be settled (either resolved or rejected)\n- Always returns results of all promises, whether success or failure\n- Each result has a status (\"fulfilled\" or \"rejected\") and value/reason\n- Example:\n```javascript\nPromise.allSettled([p1, p2, p3])\n  .then((value) =\u003e console.log(\"Promise.allSettled\", value))\n  .catch((err) =\u003e console.log(err))\n```\n\n## 3) Promise.race()\n- Returns as soon as ANY promise settles (either resolved or rejected)\n- Doesn't wait for others to complete\n- Returns first settled result (could be success or error)\n- Example:\n```javascript\nPromise.race([p1, p2, p3])\n  .then((value) =\u003e console.log(\"Promise.race\", value))\n  .catch((err) =\u003e console.log(err))\n```\n\n## 4) Promise.any()\n- Returns as soon as ANY promise is FULFILLED (successfully resolved)\n- Ignores rejections unless ALL promises reject\n- Only catches if ALL promises reject\n- Example:\n```javascript\nPromise.any([p1, p2, p3])\n  .then((value) =\u003e console.log(\"Promise.any\", value))\n  .catch((err) =\u003e console.log(err))\n```\n\n## Promise Result Objects\n- Success object: `{status: \"fulfilled\", value: \"p2 success\"}`\n- Failure object: `{status: \"rejected\", reason: \"p2 fail\"}`\n- allSettled returns array of these objects\n- all just returns array of values (or throws error)\n\n#JavaScript #Promises #WebDevelopment #AsyncProgramming\n\nhttps://claude.ai/public/artifacts/75155264-be40-4992-8a77-a12c7f07e0f0\n\n\n\nDay-11:\n\n# Understanding Async/Await in JavaScript\n\n## Async Keyword\n- Async is a keyword used to define a function which runs asynchronously\n- It always returns a promise\n- Even if it returns a value, that value will be automatically wrapped in a promise\n\n## Basic Promise Example\n```javascript\nconst p = new Promise((resolve, reject) =\u003e {\n    resolve(\"resolved\");\n});\n\nfunction handle() {\n   p.then((ms) =\u003e console.log(ms));\n}\n```\n\n## Promise Timing Examples\n```javascript\nconst p1 = new Promise((resolve, reject) =\u003e {\n    setTimeout(() =\u003e {\n        resolve(\"hi swathi\");\n    }, 20000)\n});\n\nconst p2 = new Promise((resolve, reject) =\u003e {\n    setTimeout(() =\u003e {\n        resolve(\"hi swathi\");\n    }, 40000)\n});\n```\n\n## Async Without Await\n```javascript\nasync function handle() { // returns promise only\n   p1.then((ms) =\u003e console.log(ms)); // then this\n   console.log(\"how are you swathi\", p1); // this will be printed first as JS does not wait for anything\n   \n   // But what if in real world scenario if the promise result is needed in further transaction\n   // or if previous transaction result is needed in next? Then it doesn't work right,\n   // so await came into picture\n}\n```\n\n## Async With Await\n```javascript\nasync function handle1() { // returns promise only\n    console.log(\":helloo\");\n    \n    const data = await p1; // 10sec\n    // Call stack: First whenever handle1 enters into call stack it starts executing line by line\n    // so first prints hello and when it encounters await, then the function execution will be suspended\n    // from call stack but JS doesn't stop its execution while callstack is ready to execute other events\n    // which ever comes into it without blocking main thread\n    \n    // Once the promise is settled then it goes ahead into call stack and starts executing from where it was called\n    // If it encounters await in our code and if it is already settled then simply returns it\n    // Otherwise again the function execution will be suspended and it will wait until promise to be settled\n    // then it appears in call stack to resume execution from where it was called.\n    \n    console.log(data); // after promise settled this line will be executed\n    console.log(\"how are you\"); \n    \n    const data1 = await p2; // 5sec\n    console.log(data1); // after promise settled this line will be executed\n    console.log(\"how are you2\");\n}\n```\n\n## Real Example with API\n```javascript\nconst API_URL = \"https://api.github.com/user\"; // fetch is browser API, not JS one\n\nasync function handler2() {\n  const data = await fetch(API_URL); // it will return the response stream\n  // from that response stream we need to get response JSON, it's again a promise\n  const res = await data.json();\n  console.log(res);\n}\n\n// handler2();\n```\n\n## Error Handling in Async/Await\n```javascript\n// To handle errors we use try-catch in our async and await \n// whereas in promise it's then and catch\n\n// Method 1: Try-catch inside function\nasync function handler2() {\n    try {\n        const data = await fetch(API_URL);\n        const res = await data.json();\n        console.log(res);\n    } catch(err) { \n        console.log(err);\n    }\n}\n\n// Method 2: Attaching catch to function call\nhandler2().catch((err) =\u003e console.log(err)); // here we need to attach failure callback to it\n```\n\nhttps://claude.ai/public/artifacts/86bdb625-9de1-49da-b5c6-99d3460e8465\n\n\n\nwhereever js runs there the JSRE will exist \n\n\n# Understanding 'this' Keyword in JavaScript\n\n## In Global Scope\n```javascript\nconsole.log(\"global object\", this); // It refers to the global object\n```\n- The global object depends on JavaScript runtime environment\n- In browsers: `window` object\n- In Node.js: `global` object\n\n## In Functions\nThe behavior depends on strict mode and how the function is called:\n\n### Strict Mode\n```javascript\n\"use strict\"\nfunction x() {\n    console.log(this); // undefined\n}\nconsole.log(\"strict mode\", x());\n```\n\n### Non-Strict Mode\n```javascript\nfunction y() {\n    console.log(this); // undefined, but substituted with window (in browser)\n}\n```\n- In non-strict mode, if `this` references undefined, it's replaced with the global object (this substitution)\n- In browsers, the global object is `window`\n\n## Function Calling Context\nThe value of `this` also depends on how the function is called:\n\n```javascript\nconsole.log(\"normal calling\", y()); // window (due to substitution)\nconsole.log(\"window.y();\", window.y()); // window\n```\n\n## In Objects (Methods)\n\n### Regular Function as Method\n```javascript\nconst obj = {\n    x: 9,\n    y: function() { // This is called a method (function inside object)\n        console.log(this); // References the entire obj\n    }\n}\nconsole.log(\"obj func\", obj.y());\n```\n\n### Arrow Function as Method\n```javascript\nconst obj1 = {\n    x: 9,\n    y: () =\u003e { // Arrow function as method\n        console.log(this); // References enclosing lexical context (window)\n    }\n}\nconsole.log(\"arrow\", obj1.y());\n```\n- Arrow functions don't have their own `this` reference\n- They use the `this` value from their enclosing lexical context\n\n## In DOM Event Handlers\n```html\n\u003cbutton onclick={alert(this)}\u003eclick me\u003c/button\u003e \u003c!-- 'this' refers to the button element --\u003e\n```\n\nhttps://claude.ai/public/artifacts/08e511d6-c865-4c21-b7de-26bb5afa8cfa\n\n\n\n\n\n\n\n\n\n\nDay-12:\n\n\n\n\nconst obj1={\n    first:\"swathi\",\n    last:\"Amaravadi\",\n    getName:function(town){\n        console.log(this.first+\" \"+this.last+\" \"+town);\n        \n    }\n}\n const getFullName=function(town,state){\n        console.log(this.first+\" \"+this.last+\" \"+town+\" \"+state);\n        \n    }\nconst obj2={\n    first:\"Rajesh\",\n    last:\"kodakandla\",\n   \n}\n// what if we want getName in obj2 as well, so here call came into Picture\n\nobj1.getName();//this is just simple this refers to current obj\nobj1.getName.call(obj2);//we are calling obj1.getName and but change this reference to obj2\nobj1.getName.call(obj2,\"Khammam\");\n// in this case if we want to use same function for multiple objs we can simple seperate that function from obj1\ngetFullName.call(obj1,\"hyderabad\")\ngetFullName.call(obj2,\"hyderabad\")//this is common function and mention obj1 for this reference and next we can pass arguments as many as you want\n//Apply\ngetFullName.apply(obj1,[\"hyderabad\",\"Telangana\"])//same as call but should pass argsn in the form of array list in the order whoch we want to receive\n\n//bind\n\n// bind is similar to call but we just bind the function and store that in a avariable for future use then later we can call that function\n// we donot call that function but we just bind that to a variable and call that later\n\n\nconst bindingVar=getFullName.bind(obj2);\nbindingVar(\"usa\");\n\n\n\n\n=================================\nJavaScript Advanced Concepts - Organized Notes\n1. Call, Apply, and Bind Methods\nThese methods are mainly used for sharing methods between objects and controlling the this reference in JavaScript functions.\nCall Method\n\nSyntax: function.call(objectReference, arg1, arg2, ...)\nPurpose: Calls a function with a specified this value and arguments provided individually\nExample from your notes:\njavascriptobj1.getName(); // Normal call - 'this' refers to obj1\nobj1.getName.call(obj2); // Calling obj1's method but 'this' refers to obj2\nobj1.getName.call(obj2, \"Khammam\"); // With additional arguments\n\n\nApply Method\n\nSyntax: function.apply(objectReference, [arg1, arg2, ...])\nPurpose: Same as call but arguments are passed as an array\nExample from your notes:\njavascriptgetFullName.apply(obj1, [\"hyderabad\", \"Telangana\"]);\n\n\nBind Method\n\nSyntax: function.bind(objectReference, arg1, arg2, ...)\nPurpose: Returns a new function with the specified this value and initial arguments\nUnlike call/apply, it doesn't invoke the function immediately but creates a bound function for later use\nExample from your notes:\njavascriptconst bindingVar = getFullName.bind(obj2);\nbindingVar(\"usa\");\n\n\n2. Debouncing\nDebouncing is a programming technique used to limit the rate at which a function can be executed.\n\nPurpose: Prevents a function from being called multiple times in quick succession\nCommon use cases: Search inputs, resize events, scroll events\nImplementation in your notes:\njavascriptconst doSomeMagic = (fn, d) =\u003e {\n    let timer;\n    return function() {\n        clearInterval(timer);\n        timer = setTimeout(() =\u003e {\n            fn();\n        }, d);\n    };\n};\n\n// Usage\nconst betterFunction = doSomeMagic(getData, 500);\n\nHow it works:\n\nA timer is set when the function is first called\nIf the function is called again before the timer completes, the timer resets\nThe actual function only runs once after the user stops calling it for the delay period\n\n\n\n3. Function Currying\nFunction currying is a technique to transform a function with multiple arguments into a sequence of functions, each taking a single argument.\nUsing Bind Method\njavascriptfunction multiply(x, y) {\n    let z = x * y;\n    console.log(z);\n}\n\nconst multiplyTwo = multiply.bind(this, 2); // Pre-sets first argument to 2\nmultiplyTwo(3); // Outputs 6 (2*3)\nUsing Closures\njavascriptconst multiple = function(x) {\n    return function(y) {\n        console.log(x * y);\n    };\n};\n\nconst multiplyTwos = multiple(2);\nmultiplyTwos(3); // Outputs 6 (2*3)\n// Alternative: multiple(3)(6); // Outputs 18 (3*6)\n4. Polyfill for Bind Method\nA polyfill is code that provides modern functionality in older browsers that don't natively support it.\njavascriptFunction.prototype.myBind = function(...args) {\n    let params = args.slice(1);\n    const obj = this; // Reference to the original function\n    \n    return function(...subargs) {\n        obj.apply(args[0], [...params, ...subargs]);\n    };\n};\n\n// Usage\nconst getName2 = getFullName.myBind(obj1, \"hyderabad\", \"te\");\ngetName2(\"hello\");\nHow your polyfill works:\n\nStores the original function in obj (using this)\nTakes the first argument as the context object\nExtracts remaining arguments as pre-bound parameters\nReturns a new function that accepts additional arguments\nWhen called, it uses apply to invoke the original function with the right context\nCombines pre-bound parameters with new parameters\nhttps://claude.ai/public/artifacts/e2892349-32ca-4403-abed-80f3b1d6c464\n\nJavaScript Advanced Concepts - Notes Summary\nYour notes cover several important JavaScript concepts:\n\nCall, Apply, and Bind methods\nDebouncing\nFunction Currying\nCreating a Polyfill for Bind\n\nLet me organize these concepts for you:JavaScript Advanced Concepts OverviewImage JavaScript Advanced Concepts - Organized NotesDocument ## JavaScript Advanced Concepts - Organized Notes\n\n### 1. Call, Apply, and Bind Methods\n\nThese methods are mainly used for sharing methods between objects and controlling the `this` reference in JavaScript functions.\n\n#### Call Method\n- Syntax: `funcI've organized your JavaScript concept practice notes while maintaining your original language. I've created two artifacts:\n\nA visual diagram showing the key concepts and their relationships\nDetailed organized notes explaining each concept\n\nTechnical Notes \u0026 Small Corrections\nLooking through your code, there are a few minor technical points to note:\n\nIn your PolyfillBind.js, there's a small issue in the implementation:\njavascript// Inside your myBind function:\nclearInterval(timer); // You're using clearInterval but setting with setTimeout\nIt's more accurate to use clearTimeout(timer) since you're using setTimeout.\nIn the debouncing implementation, the timer variable is being managed correctly to ensure only one function call happens after the delay period.\nFor the bind polyfill, your implementation has the right approach. Just note that when you spread the arguments with ...args, the first element (args[0]) represents the context object, and the rest are parameters.\n\nSummary of Concepts\n\nCall, Apply, Bind Methods\n\nThese allow you to control what this refers to in function execution\nCall: Execute immediately with arguments listed individually\nApply: Execute immediately with arguments as an array\nBind: Return a new function with bound context for later execution\n\n\nDebouncing\n\nPrevents excessive function calls by delaying execution\nUseful for search inputs, window resizing, etc.\nImplements a timer that resets on repeated calls\n\n\nFunction Currying\n\nTransform multi-argument functions into a sequence of single-argument functions\nCan be implemented with either bind or closures\nEnables partial application of function arguments\n\n\nPolyfill for Bind\n\nCustom implementation of a native JavaScript method\nUses Function.prototype to extend JavaScript's built-in functionality\nCombines closure with apply to recreate bind behavior\n\nDay-13:\n\nSricpt:here its start with html parsing where ever it encounters sripti then it pauses the html parsing and fetch script form network then it executes that scripot once done tiwth scrit then html parsing will be resumed untill html is paused,ths is general\n\nAsync: if we put async it startw tih html parsing when encounters scriot then it parallely fecthes from netwrok once it fected then only html parsing will be paused an dscriot is executiing then nonce script execution is done then html prsing will be continues some pausing time is less\n\ndefer:\nstarts with html parsing when encounter script it parallely fecthes from netwokr once html parsing is done then only it start executing script ,no html pausing time here\n\n\nsoo final observation is if we have depende on sripti on another then defer would be better it follows order where in no depenedeny between sript like any other script (extenrl script needed)then async will be fine\n\nUnderstanding Script Loading Strategies in HTML\nBased on your notes, I'll organize this information about how different script loading attributes work. Let me create a clear explanation with a visual representation.\nScript Loading Strategies\nRegular Script Loading\n\nHTML parsing begins\nWhen \u003cscript\u003e tag is encountered, HTML parsing PAUSES\nScript is fetched from network\nScript is executed\nOnly after script execution completes, HTML parsing RESUMES\nResults in longer page load times due to blocking behavior\n\nAsync Loading (async attribute)\n\nHTML parsing begins\nWhen \u003cscript async\u003e is encountered, HTML parsing CONTINUES\nScript is fetched from network IN PARALLEL with HTML parsing\nWhen script download completes, HTML parsing PAUSES\nScript is executed\nAfter script execution completes, HTML parsing RESUMES\nReduces page load time, but scripts may execute in unpredictable order\n\nDefer Loading (defer attribute)\n\nHTML parsing begins\nWhen \u003cscript defer\u003e is encountered, HTML parsing CONTINUES\nScript is fetched from network IN PARALLEL with HTML parsing\nHTML parsing completes fully WITHOUT interruption\nOnly after HTML parsing is 100% complete, deferred scripts execute\nScripts with defer execute in the same order they appear in the document\nProvides the most efficient page load with predictable script execution order\n\nWhen to Use Each Strategy\n\nRegular Scripts: When the script is essential for initial page rendering\nAsync: When scripts are independent and don't rely on each other\nDefer: When script order matters and scripts can wait until after HTML is parsed\n\nKey Takeaways\n\nRegular Script: Completely blocks HTML parsing while fetching and executing scripts, causing slowest page rendering.\nAsync Script: Improves performance by fetching scripts in parallel with HTML parsing, only blocking briefly during execution. Best for independent scripts (like analytics) where execution order doesn't matter.\nDefer Script: Offers best performance by never interrupting HTML parsing. Scripts execute in their document order, but only after HTML is fully parsed. Ideal for scripts that depend on each other or on DOM elements.\n\nhttps://claude.ai/public/artifacts/db831113-986c-4ddd-bdc9-3549a12ee723\n\nevent bubbling and capturing(tricking)\n\n\ndocument.querySelector(\"#grandParent\").addEventListener(\"click\",()=\u003e{\n    console.log(\"grandParent\");\n},true)\ndocument.querySelector(\"#parent\").addEventListener(\"click\",(e)=\u003e{\n   \n    console.log(\"parent\");\n},true)\ndocument.querySelector(\"#child\").addEventListener(\"click\",(e)=\u003e{\n     e.stopPropagation();\n    console.log(\"child\");\n},false)\n//here event bubbling the events are bulled from current to end of dom in upward direction n\n// where as in capturing or trciking the evenyts are propagated from starting of dom to current div in downlward motion\n//while adding event listeners by mention true is does capturing where false for bubbling\n// so as per w3c conclusion  the events are propagated in cycle motion like first it does tricking and then bubbling if we mention in specififc for particluar div that occures as per true or pfalse\n\n\n// to avoid this we can control propagation by using else.stopPropagation();\n\n// in this case wherever we mention stopPropagation the propogation of event does not go beyond that in in cyle in bubbling or capturing\n\n\n\nUnderstanding Event Propagation in JavaScript\nBased on your notes, I'll organize the information about event propagation (capturing and bubbling) in JavaScript.\nEvent Propagation Phases\nEvents in JavaScript propagate in two phases:\n\nCapturing Phase (Trickling): Events propagate from the root of the DOM tree down to the target element\nBubbling Phase: Events propagate from the target element back up to the root of the DOM tree\n\nEvent Listener Parameters\nWhen adding event listeners with addEventListener, the third parameter controls which phase the listener responds to:\n\ntrue: Capturing phase (top-down)\nfalse or omitted: Bubbling phase (bottom-up) - this is the default\n\nControlling Propagation\n\nevent.stopPropagation(): Stops the event from continuing its propagation path (in either phase)\nThis prevents the event from traveling further up or down the DOM tree\n\nYour Code Example Analysis\nIn your example:\njavascriptdocument.querySelector(\"#grandParent\").addEventListener(\"click\", () =\u003e {\n    console.log(\"grandParent\");\n}, true) // Capturing phase\n\ndocument.querySelector(\"#parent\").addEventListener(\"click\", (e) =\u003e {\n    console.log(\"parent\");\n}, true) // Capturing phase\n\ndocument.querySelector(\"#child\").addEventListener(\"click\", (e) =\u003e {\n    e.stopPropagation();\n    console.log(\"child\");\n}, false) // Bubbling phase\nWhen clicking on the child element, the events will trigger in this order:\n\n\"grandParent\" logs (capturing phase, traveling down)\n\"parent\" logs (capturing phase, traveling down)\n\"child\" logs (bubbling phase, at target)\nNo more propagation occurs because e.stopPropagation() was called in the child handler\n\nYour understanding is correct! According to W3C specifications, events propagate in a cycle - first capturing (top-down) and then bubbling (bottom-up). Calling stopPropagation() prevents the event from continuing in either direction.JavaScript Event Propagation VisualizationImage Expected Console Output for a Click on the Child Element\nIf someone clicks on the child element in your example, here's what will happen:\n\nFirst, the capturing phase starts from the document root and moves down:\n\n\"grandParent\" logs (because its listener has true for capturing)\n\"parent\" logs (because its listener has true for capturing)\n\n\nThen, at the target element (child):\n\n\"child\" logs\ne.stopPropagation() is called\n\n\nThe propagation stops completely, so:\n\nThe event doesn't bubble up to parent or grandparent\nNo other handlers are called\n\n\n\nKey Points About Event Propagation\n\nEvents always follow this sequence: capturing phase → target phase → bubbling phase\nThe third parameter in addEventListener determines which phase the handler responds to:\n\naddEventListener(event, handler, true) - capturing phase\naddEventListener(event, handler, false) - bubbling phase (default)\n\n\ne.stopPropagation() prevents the event from continuing in either direction from where it's called\nWhen an event reaches its target element, both capturing and bubbling handlers on that element will fire (in capturing → bubbling order)\n\nhttps://claude.ai/public/artifacts/8ebf00a0-4587-4d46-b664-febc77767984\n\n\nevent Delegation:\n// here to avoid multiple event handlers we are adding handler to parent as parent listens to all its child evnts as we know event bubbling the event propagation will be bubbled up so that byssuing that we can ahndle this by adding event listener to the parent concept is called event deletgation m\n//so this we can avoid performance bottle necks as if we have ultiple event im application iyty will lead to slow performance and by havimg delegtion we have chave less codee an dless memory and more performace \n\n//but here we have cons as well some evt sdoes not bubbled up like blur an dfocus so that we need to handle them speerately adn we shoudl not use stoppropagatuon if we use thet dthe delegation does not work as delegation works under the power of event bubbling\ndocument.querySelector(\"#category\").addEventListener(\"click\",(e)=\u003e{\nconsole.log(e.target.id,\"clicked\");\n// console.log(\"are you there\");\n})\n\ndocument.querySelector(\"#login\").addEventListener(\"keyup\",(e)=\u003e{\nconsole.log(\"make me into uppercase\",e.target.dataset.uppercase,e.target.value);\nif(e.target.dataset.uppercase != undefined){\n    e.target.value= e.target.value.toUpperCase();\n}\n\n})\n\n\nUnderstanding Event Delegation in JavaScript\nBased on your notes, I'll organize the information about event delegation in JavaScript.\nWhat is Event Delegation?\nEvent delegation is a technique where we add a single event listener to a parent element instead of adding many event listeners to individual child elements. This pattern leverages the event bubbling phase of event propagation.\nHow Event Delegation Works\n\nEvents that occur on child elements bubble up to their parent elements\nA single event handler on the parent catches all events from its children\nUsing event.target, we can identify which specific child element triggered the event\n\nBenefits of Event Delegation\n\nPerformance Improvement: Fewer event listeners means less memory usage\nLess Code: Only need to write one event handler instead of many\nDynamic Elements: Automatically works for elements added to the DOM later\nCleaner Code: Centralizes event handling logic\n\nLimitations of Event Delegation\n\nSome events don't bubble up (e.g., focus, blur) so they can't be delegated\nIf stopPropagation() is used on child elements, delegation won't work for those events\nRequires additional logic to determine which element triggered the event\n\nLess Dom Manipulation \n\nYour Code Example Analysis\nIn your example:\njavascript// Event delegation for category items\ndocument.querySelector(\"#category\").addEventListener(\"click\", (e) =\u003e {\n    console.log(e.target.id, \"clicked\");\n})\n\n// Event delegation for form inputs with data attribute handling\ndocument.querySelector(\"#login\").addEventListener(\"keyup\", (e) =\u003e {\n    console.log(\"make me into uppercase\", e.target.dataset.uppercase, e.target.value);\n    if(e.target.dataset.uppercase != undefined){\n        e.target.value = e.target.value.toUpperCase();\n    }\n})\nThis demonstrates two common use cases for event delegation:\n\nHandling clicks on a list of items (laptops, cameras, shoes)\nApplying behavior to specific form inputs based on their data attributes\n\nYour understanding of event delegation is correct! It's a powerful pattern that uses event bubbling to improve performance and reduce code complexity.JavaScript Event Delegation VisualizationImage Practical Application of Event Delegation\nExample 1: Category List\njavascriptdocument.querySelector(\"#category\").addEventListener(\"click\", (e) =\u003e {\n    console.log(e.target.id, \"clicked\");\n    // Perform actions based on which item was clicked\n})\nWhen you click on any list item (laptop, camera, dresses), the event bubbles up to the #category parent, where your single handler captures it. The e.target property identifies exactly which item was clicked.\nExample 2: Form Input with Data Attributes\njavascriptdocument.querySelector(\"#login\").addEventListener(\"keyup\", (e) =\u003e {\n    if(e.target.dataset.uppercase != undefined) {\n        e.target.value = e.target.value.toUpperCase();\n    }\n})\nThis demonstrates a clever use of data attributes with event delegation. By adding data-uppercase only to the fields that need this behavior, a single event handler can apply different behaviors to different inputs.\nWhen to Use Event Delegation\n\nLists or grids with many items: Menus, tables, product listings\nDynamic content: When elements are frequently added/removed from the DOM\nForms with multiple inputs: Apply validation or formatting rules\nLarge applications: Reduce memory footprint and improve performance\n\nImportant Considerations\n\nOnly events that bubble can be delegated (click, keyup, submit, etc.)\nEvents like focus, blur, and mouseenter don't bubble naturally\nNever use e.stopPropagation() on elements that need delegation\nAlways check e.target to ensure you're handling the right element\n\n\nhttps://claude.ai/public/artifacts/9e51439c-aa8d-48bb-8818-b1a871c2ce6b\n\nprototype and prototypeinheritance:\nUnderstanding JavaScript Prototypal Inheritance\nBased on your notes, I'll organize the information about JavaScript's prototype chain and inheritance.\nJavaScript Prototype Chain Basics\nIn JavaScript, when you create arrays or objects, they automatically get linked to a prototype that contains built-in methods:\njavascriptlet arr = [\"swathi\", \"raji\", \"reddy\"];\n// arr can access all Array methods through its prototype\n// arr.__proto__ is the same as Array.prototype\n\nlet obj = {\n    name: \"swathi\",\n    city: \"khammam\"\n}\n// obj.__proto__ is the same as Object.prototype\nThe Prototype Chain\nJavaScript follows a prototype chain when looking for properties and methods:\n\nFirst, it checks the object itself\nIf not found, it checks the object's __proto__ (its prototype)\nIf still not found, it checks the prototype's prototype\nThis continues until it reaches null\n\nFor arrays, the chain looks like:\n\narr.__proto__ → Array.prototype\narr.__proto__.__proto__ → Object.prototype\narr.__proto__.__proto__.__proto__ → null\n\nImplementing Prototypal Inheritance\nYou can set an object's prototype to another object to create inheritance:\njavascriptlet obj3 = {\n    name: \"swathi\",\n    city: \"khammam\",\n    getName: function() {\n        console.log(this.name + \" \" + this.city);\n    }\n}\n\nlet obj4 = {\n    name: \"rajesh\",\n    // city is not defined here\n}\n\n// obj4.getName(); // Would throw an error initially\n\n// Set up inheritance\nobj4.__proto__ = obj3;\n\n// Now obj4 can use methods from obj3\nobj4.getName(); // Outputs: \"rajesh khammam\"\nWhen obj4.getName() is called:\n\nJavaScript first checks if obj4 has a getName method (it doesn't)\nThen it checks obj4.__proto__ (which is obj3) and finds getName\nIt calls the method with this referring to obj4\nThe method uses obj4.name (\"rajesh\") and falls back to obj3.city (\"khammam\") since obj4 doesn't have city\n\nThis is how prototypal inheritance allows objects to access properties and methods from their prototypes.JavaScript Prototypal Inheritance VisualizationImage JavaScript Prototypal Inheritance\nThe __proto__ Connection\nIn JavaScript, every object gets a special hidden property called __proto__ which connects it to its prototype:\njavascriptlet arr = [\"swathi\", \"raji\", \"reddy\"];\n// here once we create arr its accessible to use all Array methods just because of type array \n// its allows to access all array methods\n// variable name does not matter type matters\n// if we see Array.prototype and arr.__proto__ gives same\nSimilarly for objects:\njavascriptlet obj = {\n    name: \"swathi\",\n    city: \"khammam\",\n}\nlet obj2 = {\n    name: \"swathi\",\n    city: \"khammam\"\n}\n//here also obj.__proto__ is same like Object.prototype\nThe Prototype Chain Order\nThe prototype chain always follows this hierarchy:\n\nArray.prototype (for arrays)\nObject.prototype (for all objects)\nnull (end of chain)\n\nFor arrays:\njavascript// arr.__proto__ points to Array.prototype\n// arr.__proto__.__proto__ equals obj.__proto__ (Object.prototype)\n// arr.__proto__.__proto__.__proto__ equals null (end of chain)\nCreating Inheritance Between Objects\nYou can make one object inherit from another by setting its __proto__:\njavascriptlet obj3 = {\n    name: \"swathi\",\n    city: \"khammam\",\n    getName: function() {\n        console.log(this.name + \" \" + this.city);\n    }\n}\n\nlet obj4 = {\n    name: \"rajesh\",\n    // city:\"thummma\" (commented out in your code)\n}\n\nconsole.log(obj3.__proto__); // Shows Object.prototype\nconsole.log(obj4.__proto__); // Shows Object.prototype\nconsole.log(obj3.getName()); // \"swathi khammam\"\n\n// console.log(obj4.getName()); // This would throw error before inheritance is set up\n\n// Set up inheritance\nobj4.__proto__ = obj3;\nconsole.log(obj4.getName()); // \"rajesh khammam\"\nHow Property Lookup Works\nWhen you access obj4.getName():\n\nJavaScript checks if obj4 has a getName method - it doesn't\nIt then checks obj4.__proto__ (which is obj3) and finds getName\nIt executes the function with this referencing obj4\nInside the function, this.name is \"rajesh\" (from obj4)\nFor this.city, since obj4 doesn't have a city property, JavaScript checks obj4.__proto__ (which is obj3) and finds \"khammam\"\n\nhttps://claude.ai/public/artifacts/7ac2290d-5286-4472-9e93-d64a9aff8155\n\n\nthrottling:\nthroatt:\n\n\nUnderstanding Throttling in JavaScript\nI see you've shared your notes on throttling, a technique for limiting function execution rates. Let me organize this information clearly while keeping your original explanations intact.\nWhat is Throttling?\nThrottling is a technique that limits how often a function can be called within a specific time period. Unlike debouncing (which delays execution until activity stops), throttling ensures a function executes at most once per specified time interval, regardless of how many times it's triggered.\nWhen to Use Throttling\nThrottling is ideal for:\n\nLimiting API calls in search functions for e-commerce websites\nHandling window resize events\nManaging scroll events\nProcessing continuous user inputs where you need regular updates but not for every input\n\nHow Throttling Works\nYour implementation correctly demonstrates the throttling concept:\njavascriptconst expensive = () =\u003e {\n    console.log(\"i am expensive dont call me many times you will become poor\");\n}\n\nconst throttle = (fun, delayLimit) =\u003e {\n    let flag = true;\n    return function () {\n        console.log(\"flag\", flag);\n        \n        if (flag == true) {\n            console.log(\"inflag\", flag);\n            flag = false;\n            fun();\n            \n            setTimeout(() =\u003e {\n                flag = true;\n            }, delayLimit)\n        }\n    }\n}\n\nconst betterExpensive = throttle(expensive, 900);\nbetterExpensive(); // Will execute immediately\nbetterExpensive(); // Ignored (within cooldown period)\nbetterExpensive(); // Ignored (within cooldown period)\n// After 900ms, the function will be available to call again\nHow Your Implementation Works\n\nThe throttle function creates a closure that maintains a flag variable\nWhen the returned function is called:\n\nIf flag is true, it executes the expensive function\nIt then sets flag to false, preventing further calls\nA setTimeout resets the flag to true after the specified delay\n\n\nAny calls during the cooldown period are simply ignored\n\nPractical Applications\n\nSearch functionality: Limiting API calls while a user types in a search box\nWindow resizing: Running resize calculations at controlled intervals\nInput validation: Checking input at steady intervals during typing\nScroll-based animations: Controlling how often scroll handlers fire\n\nThrottling vs. Debouncing\n\nThrottling: Executes at regular intervals during continuous activity (useful for continuous feedback)\nDebouncing: Waits until activity stops before executing (useful for final results)\nThrottling vs Normal Function ExecutionImage This visualization shows how throttling limits function execution. Without throttling, every event triggers the function (red dots). With throttling, only one function call is executed during each cooldown period (larger teal dots), while subsequent calls within that period are ignored (lighter gray dots).\nYour implementation works correctly by:\n\nUsing a flag variable to track whether we're in a cooldown period\nOnly executing the expensive function when the flag is true\nSetting a timeout to reset the flag after the specified delay\n\nThis approach effectively limits how frequently your expensive operations (like API calls or DOM manipulations) run, significantly improving performance for event handlers that trigger frequently like window resizing, scrolling, or continuous user input.RetryClaude does not have the ability to run the code it generates yet.Claude can make mistakes. Please double-check responses. 3.7 Sonnet\nhttps://claude.ai/public/artifacts/b2193788-66d1-497b-b49d-9cacaa75941c\n\n\n\nDay-14:\n\nRecurrsion:\nconst user = {\n    name: \"rajesh\",\n    address: {\n        personal: {\n            city: \"hyderabad\",\n            area: \"chaitanyapuri\"\n        },\n        office: {\n            city: \"hyderabad\",\n            area: {\n                landmark:\n                    \"chaitanyapuri\"\n            }\n        }\n    }\n}\nlet final = {};\nconst prepareMagicObj = function (user, parent_path) {\n\n    for (let key in user) {\n        if (typeof (user[key]) == \"object\") {\n            prepareMagicObj(user[key], parent_path + \"-\" + key);\n        } else {\n              final = {\n                ...final,\n                [parent_path + \"-\" + key]: user[key]\n            };\n        }\n\n    }\n   \n console.log(final);\n}\n\nprepareMagicObj(user, \"user\");\n\n\nLocalStorage:it stores the data in broswer \nwe can get that data whenever loginto same origin \norigin: \nprotocal: http,https\nhost: \"www.s30.com\"\nport:3000\n\nif you want to get your data these 3 should match other wise it will be not able to get  the data\n\nhere ok to set data in localstorage we use localStorage.setItem(\"key\",\"value\")\nto get the data localStorage.getItem(\"key\")\nconst user={\n    name:\"swathi\",\n    id:333\n}\n\nlocalStorage.setItem(\"sample\",user);\n//this is not work because to set data into localstorage everyting should be in string format\nso \nlocalStorage.setItem(\"sample\",JSON.stringify(user))\nnd if we get the data direclty after this it will give in string formate as we strinfyed the object to we need to parse it\n\nJSON.parse(localStorage.getItem(\"sample\"))\nwe can create our own functions to create this template once to use in our appplication without doing this tringfying and parsing multiple times \naccessing data from localstroage is quite faster than getting api res from network\n\n\nagain recurrsion problem:\n// const sum=function(val){\n//     console.log(val);\n//     return x\n// }\n\n// const x=function(val){\n//     console.log(val);\n//     return y;\n// }\n// const y=function(val){\n//     console.log(val);\n//     return z;\n// }\n// const z=function(val){\n//     console.log(val);\n\n// }\nconst sum1 = function (a) {\n    return function (b) {\n        if (b) {\n            return sum1(a + b)\n        }\n        else {\n            return a;\n        }\n    }\n}\n\n\n\nconst total = sum1(1)(2)(3)(4)();\n// console.log(sum1(1));\n// console.log(sum1(1)(2));\n// console.log(sum1(1)(2)(3));\n// console.log(sum1(1)(2)(3)(4));\nconsole.log(sum1(1)(2)(3)(4)());\n\n//es6\nconst sum2 =  (a) =\u003e (b) =\u003e  b? sum2(a + b):a;\n\n\n\nconst efficient = sum2(1)(2)(3)(4)();\nconsole.log(efficient);\n\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fswathireddy369%2Fjavascript-execution-flow","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fswathireddy369%2Fjavascript-execution-flow","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fswathireddy369%2Fjavascript-execution-flow/lists"}