<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Savinu Vijay on Medium]]></title>
        <description><![CDATA[Stories by Savinu Vijay on Medium]]></description>
        <link>https://medium.com/@savinu.vijay?source=rss-42f4f50cc853------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hVOaDoWVKwAWznxx50XnXg.jpeg</url>
            <title>Stories by Savinu Vijay on Medium</title>
            <link>https://medium.com/@savinu.vijay?source=rss-42f4f50cc853------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 19:13:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@savinu.vijay/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What If AI Evolved Like Human Civilization?]]></title>
            <link>https://medium.com/@savinu.vijay/what-if-ai-evolved-like-human-civilization-5832b3238b8d?source=rss-42f4f50cc853------2</link>
            <guid isPermaLink="false">https://medium.com/p/5832b3238b8d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Savinu Vijay]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 13:04:12 GMT</pubDate>
            <atom:updated>2026-07-21T13:04:12.651Z</atom:updated>
            <content:encoded><![CDATA[<h4>Rethinking intelligence through specialization, coordination, and distributed expertise.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*woAjKf-E6l8LwJjbWMGo1w.png" /></figure><p>Every new generation of AI becomes more capable than the one before it. It writes better code, solves harder problems, and expands into new domains that once seemed beyond its reach.</p><p>Progress is often measured by a simple question:</p><blockquote>How much more can a single model do than the one before it?</blockquote><p>It’s a compelling way to measure progress, and it has driven remarkable breakthroughs. But it also raises an interesting question.</p><blockquote>Why do we expect a single language model to become an expert at everything?</blockquote><p>In fact, no other intelligent system we know of works this way.</p><h3>The World Already Solved This Problem</h3><p>Imagine walking into a hospital.</p><p>A patient arrives with chest pain. The diagnosis isn’t made by one extraordinary doctor. Instead, it emerges through collaboration.</p><figure><img alt="The Hospital Analogy" src="https://cdn-images-1.medium.com/max/565/1*z5GQmOAlmgtzGSIiNr9FPQ.png" /></figure><p>A general physician performs the initial assessment. A cardiologist examines the heart. A radiologist interprets the scans. A pathologist analyzes laboratory findings. The treatment is based on the conclusions from all these specialists.</p><p>Every specialist contributes deep knowledge within a narrow domain. No one expects the cardiologist to also be the world’s best neurologist or a radiologist to perform surgery.</p><p>In fact, expecting every doctor to master every branch of medicine; would make the healthcare system less effective, not more.</p><p>Medicine isn’t unique. The same principle appears across human civilization — from <strong>filmmaking</strong> and building <strong>skyscrapers</strong> to advancing <strong>scientific discovery</strong>.</p><p>This isn’t a limitation of human intelligence. It’s the very reason civilization works. As knowledge grows, expertise becomes more specialized.</p><p>As expertise becomes more specialized, solving complex problems depends less on finding someone who knows everything, and more on bringing together the <strong>right experts</strong>.</p><p>This way, <strong>intelligence</strong> scales through <strong>collaboration</strong> rather than universality.</p><h3><strong>The Current Direction of AI</strong></h3><p>Today’s AI models largely pursue a different philosophy.</p><p>Each generation aims to become more capable across as many domains as possible.</p><p>The broader the capabilities, the more impressive the model appears. This approach has produced incredible systems.</p><p>General-purpose models are already capable of performing tasks that seemed impossible just a few years ago. But success has also reinforced an implicit assumption, that is:</p><blockquote>The future of AI is <strong>one</strong> increasingly capable model that eventually becomes good at everything.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*hGE3idAxF0-cT6EBEjB3Ig.png" /><figcaption>Current General-Purpose models</figcaption></figure><p>It’s an intuitive assumption. But it stands in contrast to almost every successful complex system humanity has ever built.</p><blockquote><em>When civilization faced increasingly difficult problems, we didn’t create </em><strong><em>universal experts</em></strong><em>. We created </em><strong><em>specialists </em></strong><em>and then learned how to </em><strong><em>coordinate</em></strong><em> them.</em></blockquote><h3><strong>Organizing Intelligence</strong></h3><p>Consider designing a skyscraper. We don’t ask one person to do everything. Instead, a <strong>project manager</strong> coordinates experts across multiple disciplines.</p><figure><img alt="Designing a skyscraper" src="https://cdn-images-1.medium.com/max/1024/1*NgG_iIjpcJMmkuhiUBqmZg.png" /></figure><p>Now, imagine asking this AI system to do the same. Rather than sending the entire task to one enormous model, the request should first reach an <strong>Executive Model</strong>.</p><p>The <strong>Executive Model</strong> isn’t expected to know everything. Its primary expertise is to:</p><ul><li>Understand the problem clearly.</li><li>Identify the specialists required.</li><li>Decompose the problem into workable units.</li><li>Delegate work to specialists.</li><li>Coordinate their contributions.</li><li>Synthesize the solution.</li></ul><p>In other words, the <strong>Executive Model</strong> possesses broad foundational knowledge while <strong>specializing in coordination itself</strong>.</p><p>Instead of viewing intelligence as something contained within a single model, it may be viewed as a group<strong> </strong>of<strong> specialized models</strong> working together.</p><p>I think of this as the <strong>Collective Intelligence Architecture</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHSMxt4g_5ASOO0Io9XVRw.png" /><figcaption>Collective Intelligence Architecture</figcaption></figure><p>Rather than concentrating intelligence within one increasingly capable model, <strong>Collective Intelligence Architecture</strong> distributes intelligence across an <strong>Ecosystem of Specialist Models</strong>.</p><p>This perspective <strong>differs from today’s multi-agent systems</strong> which often coordinate multiple agents powered by the <strong>same underlying model.</strong> Their roles may differ, but they rely on the same core intelligence.</p><p>The idea explored here imagines an ecosystem of <strong>genuinely specialized models</strong>, each developed to become exceptionally capable within a <strong>particular domain</strong>, working together to solve problems.</p><blockquote>Just as civilization became more capable by <strong>organizing expertise</strong> rather than concentrating it in individuals, future AI systems may become more capable by <strong>organizing specialized intelligence</strong> rather than endlessly expanding a single general-purpose model.</blockquote><h3><strong>Creating Expertise</strong></h3><p>Human civilization has developed institutions dedicated to creating expertise.</p><p>Universities educate specialists. These specialists then join organizations and form teams based on the problems they need to solve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*vcz5lM0DHwMAhCZ-CXNhuw.png" /></figure><p>AI ecosystems could also evolve in a similar way.</p><p>There may be AI Labs that are dedicated to creating the world’s best <strong>specialist models </strong>in a particular domain.</p><p>One lab may develop exceptional <strong>legal </strong>models, while another might focus exclusively on <strong>medicine</strong>. Another lab may produce models in <strong>cybersecurity,</strong> while others become known for their models specialized in climate science, robotics, mathematics, finance, engineering, or education.</p><p>Competition among AI Labs may shift from building the <strong>most general model</strong> to building the world’s best <strong>specialist model</strong> within a particular domain.</p><p>Now, instead of asking,</p><blockquote>“Who built the <strong>biggest model</strong>?”</blockquote><p>we might begin asking,</p><blockquote>“Who built the world’s best <strong>medical model</strong>?”</blockquote><blockquote>“Who built the world’s best <strong>architecture model</strong>?”</blockquote><blockquote>“Who built the world’s best <strong>legal model</strong>?”</blockquote><h3><strong>The Benefits of Specialization</strong></h3><p>If intelligence is organized through specialization, its benefits extend far beyond architecture. It changes how organizations adopt AI, how systems evolve over time, and what becomes possible once expertise is organized rather than concentrated.</p><h4><strong>Modular Adoption</strong></h4><p>Organizations may no longer need to adopt one increasingly general model. Instead, they could assemble their own <strong>society of expertise</strong> by integrating only the <strong>specialist models</strong> most relevant to their domain.</p><ul><li>A hospital might prioritize medical specialists.</li><li>A law firm could build around legal specialists.</li><li>A manufacturing company might integrate engineering, supply chain, and robotics specialists.</li></ul><p>As the architecture becomes <strong>modular</strong>. Organizations pay for the expertise they actually use rather than carrying capabilities they may never need.</p><h4><strong>Incremental Evolution</strong></h4><p>This modularity also changes how organizations <strong>improve </strong>their AI systems.</p><p>Today, adopting a better model often means <strong>replacing an entire system</strong>.</p><p>In a society of specialists, organizations can upgrade <strong>individual experts</strong> while leaving the rest of the ecosystem unchanged. Improvement becomes <strong>continuous and incremental</strong> rather than monolithic.</p><h4><strong>Beyond Model Capability</strong></h4><p>The implications of specialization extend beyond how AI systems are built. They could also reshape how AI is deployed, where computation happens, and how organizations manage sensitive data.</p><p>Training frontier models, however, would likely continue to require large-scale data centers. But once trained, specialist models may become efficient enough to run locally, as each model focuses on a narrower domain.</p><p>This could allow organizations in sensitive domains such as healthcare, finance, government, and defense to keep data within their own environments while still benefiting from sophisticated AI capabilities.</p><p>In this scenario, the role of <strong>cloud infrastructure</strong> changes. Instead of handling every AI request, it primarily <strong>trains, distributes, and updates</strong> specialist models.</p><p>If such a transition occurs, organizations could reduce operational costs, improve privacy, lower latency, and become less dependent on ever-expanding cloud infrastructure. Over time, using computational resources more efficiently could also reduce the environmental impact of AI.</p><h3>Questions Worth Exploring</h3><p>This idea raises more questions than answers.</p><ul><li>How should specialist models communicate?</li><li>How should knowledge be shared without unnecessary duplication?</li><li>Who decides which specialists participate?</li><li>How is trust established between independently developed models?</li><li>Can specialist models challenge one another’s conclusions?</li><li>Can entirely new expertise emerge through collaboration?</li></ul><p>And perhaps the biggest question of all:</p><blockquote>If intelligence emerges through coordinated expertise rather than individual capability, <strong>where does intelligence actually reside?</strong></blockquote><blockquote>Is it within the individual models? Or in the system that brings them together?</blockquote><p>I don’t know the answers. But history offers an interesting observation.</p><p>Human civilization became extraordinarily capable not because individuals became experts at everything, but because society learned to organize expertise.</p><p>Perhaps the future of AI may not be defined by a <strong>single model</strong> that knows everything. It may be defined by systems that know how to bring the <strong>right expertise together</strong>.</p><blockquote>Because intelligence doesn’t always grow by becoming <strong>bigger</strong>. Sometimes it grows by becoming <strong>better organized</strong>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5832b3238b8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The AI Productivity Paradox]]></title>
            <link>https://medium.com/@savinu.vijay/the-ai-productivity-paradox-f77125ec7030?source=rss-42f4f50cc853------2</link>
            <guid isPermaLink="false">https://medium.com/p/f77125ec7030</guid>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Savinu Vijay]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 05:30:21 GMT</pubDate>
            <atom:updated>2026-06-20T05:30:21.259Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>The AI Productivity Paradox: Who Benefits from the Surplus?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wM0LKkOqud_R09qUpwR7Hw.jpeg" /></figure><p>Every discussion about AI eventually reaches the same question:</p><blockquote>“Will AI take our jobs?”</blockquote><p>This might be the wrong question to ask. The real question is:</p><blockquote>When AI makes people more productive, who gets the benefit of that productivity?</blockquote><p>Let’s take a simple example.</p><p>Imagine a company with three software developers. Each developer takes three hours to complete a task. During a six-hour workday, each developer completes two tasks. Together, the team produces six units of work per day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dcMWteZTFlFLid4nyq8oEQ.png" /></figure><p>Now the company introduces <strong>AI tools</strong>. The same task that previously took three hours can now be completed in one hour. This can increase the team’s capacity to eighteen units of work per day from six units, without changing the number of employees or working hours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPPai9JCb95nqvFBTzzTFQ.png" /></figure><p>AI has not merely improved productivity. It has created something valuable:</p><p><strong>Twelve additional units of productive capacity.</strong></p><p>This is what I call <strong>Surplus Productivity</strong> <strong>— the additional productive capacity created by AI.</strong></p><p>AI doesn’t just create productivity. It creates <strong>surplus productivity</strong>. The real question is <strong>who benefits from it</strong>.</p><h3><strong>Option 1: The Shareholder Path</strong></h3><p>One possibility is to maintain the original output.</p><p>The company only needs six units of work per day. Since AI has dramatically improved productivity, fewer employees are now required to achieve that output. Instead of retaining all three developers, the company may choose to <strong>retain only one </strong>and use AI to maintain the same level of productivity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h83Gb15hf2LwA-mMlvVD4Q.png" /></figure><p>The outcome is simple:</p><ul><li>Output remains at 6 units per day.</li><li>Labor costs decrease.</li><li>Profit margins improve.</li></ul><p>The surplus productivity is converted into <strong>cost savings</strong>.</p><p>From a business perspective, this is a perfectly rational decision. Investors are happy as the costs go down and the return on investment is easy to measure. This is the scenario that most people imagine when they worry about <strong>AI replacing jobs</strong>.</p><p>In this case, AI creates enough surplus productivity that maintaining the same output no longer requires the same workforce. The surplus is captured primarily by <strong>shareholders</strong> and <strong>business owners</strong>.</p><p>However, this approach comes with its own risks. Organizations may become overly dependent on the remaining employees. Those employees may face greater pressure to maintain output and preserve critical knowledge. As expertise becomes concentrated among a smaller group of people, the organization may become less resilient when someone leaves. The company becomes leaner, but it may also become more fragile.</p><h3><strong>Option 2: The Growth Path</strong></h3><p>A second possibility is to keep the <strong>workforce intact</strong> and <strong>increase output</strong>. Instead of producing six units per day, the company may decide to produce fifteen, or even eighteen units.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbbSLRC7chBpFhPpeY2Nhw.png" /></figure><p>The outcome looks very different:</p><ul><li>Employees keep their jobs.</li><li>Output increases significantly.</li><li>New products can be built faster.</li><li>More customers can be served.</li></ul><p>The surplus productivity is converted into <strong>business growth</strong>. This approach is often presented as the ideal outcome of technological progress. AI enables organizations to accomplish more without proportionally increasing costs.</p><p>However, this path comes with a challenge. Creating more output is easy, but finding customers who are willing to pay for that additional output is much harder. The productivity gains alone do not guarantee growth. Producing more is only valuable if there is demand for what is being produced.</p><h3><strong>Option 3: The Balanced Path</strong></h3><p>There is also a third possibility. Instead of maximizing output or reducing headcount, organizations can choose a <strong>balanced approach.</strong></p><p>Rather than converting every unit of surplus productivity into additional output, they use AI to achieve meaningful growth while maintaining a sustainable workload.</p><p>For example, instead of increasing output from six units to the theoretical maximum of eighteen units, the company may target twelve units.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*stBFpq5myo_weUVJxji3vg.png" /></figure><p>The outcome looks something like this:</p><ul><li>Output increases significantly compared to the pre-AI baseline.</li><li>Employees avoid excessive workload and burnout.</li><li>Teams have more time for learning, experimentation, and innovation.</li><li>The organization remains productive while preserving long-term sustainability.</li></ul><p>In this model, surplus productivity is <strong>shared</strong>.</p><p>While a part of it is converted into business growth, another part of it improves the working experience of employees. The organization benefits from increased output while avoiding some of the risks associated with relentless productivity pressure.</p><p>Before we continue, it is worth noting that the numbers used throughout this article are purely illustrative.</p><p>In reality, AI may not increase productivity by a fixed multiplier. The impact varies significantly depending on the nature of the work, the quality of the tools, and how effectively they are used. In some situations, the gains may be modest. In others, they may be substantial.</p><p>The purpose of this example is not to argue that AI will always make people three times more productive. It is to highlight a broader principle of how the surplus productivity is distributed.</p><h3><strong>The Hidden Debate</strong></h3><p>Most AI discussions focus on the technology itself. We compare models, benchmarks, reasoning capabilities, and coding performance. But the long-term impact of AI may have very little to do with AI itself. The deeper question is economic.</p><blockquote>When AI creates surplus productivity, how should that surplus be distributed?</blockquote><ul><li>Should it primarily benefit shareholders?</li><li>Should it fuel business growth?</li><li>Should it improve employee well-being?</li><li>Or should it be shared among all three groups?</li></ul><p>These are not technological questions. They are human questions. AI does not answer them. People do.</p><h3><strong>Looking Back</strong></h3><p>This is not the first time society has faced this challenge. Throughout history, new technologies have increased productivity. Factories automated manual labor. Computers automated calculations. The internet automated communication and information sharing.</p><p>Because of this, some jobs disappeared, while many new ones emerged. Entire industries were created centered around these new technologies.</p><p>When every major technological shift created surplus productivity, the society had to decide how that surplus would be used.</p><ul><li>Some of it became profit.</li><li>Some of it became economic growth.</li><li>Some of it became better working conditions, shorter workweeks, and improved quality of life.</li></ul><p>AI may simply be the latest chapter in that story.</p><h3><strong>Conclusion</strong></h3><p>AI does not merely automate tasks or eliminate jobs. Nor does it automatically create prosperity. What AI actually creates is <strong>surplus productivity</strong>. The future impact of AI will depend on how organizations choose to use that surplus.</p><p>One path focuses on maintaining the same output with fewer people, converting surplus productivity into cost reduction. Another path focuses on achieving greater output with the same workforce, converting surplus productivity into growth. A third path seeks a balance between growth, profitability, and sustainable workloads, allowing the benefits of AI to be shared more broadly.</p><p>None of these paths is inherently right or wrong. All are rational business decisions. But they lead to very different outcomes for businesses, employees, and society.</p><p>The debate about AI should not be limited to what the technology can do. It should also include a discussion about how we choose to distribute the value it creates.</p><blockquote>Because AI may not determine the future of work.</blockquote><blockquote>How we choose to use its surplus productivity just might.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f77125ec7030" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What If LLMs Were Just the CPU? Rethinking AI Systems as Programs]]></title>
            <link>https://medium.com/@savinu.vijay/what-if-llms-were-just-the-cpu-rethinking-ai-systems-as-programs-df926f58bd0a?source=rss-42f4f50cc853------2</link>
            <guid isPermaLink="false">https://medium.com/p/df926f58bd0a</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Savinu Vijay]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 02:29:01 GMT</pubDate>
            <atom:updated>2026-06-07T01:51:53.799Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0JfbkFS9NHF5lv_VkdFP_w.png" /></figure><p>Most AI frameworks today place the language model at the center of the system, and everything revolves around the LLM.</p><blockquote>Need knowledge? Add RAG.</blockquote><blockquote>Need external actions? Add tools.</blockquote><blockquote>Need memory? Add a memory layer.</blockquote><blockquote>Need autonomy? Add agents.</blockquote><p>The result often looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*dn_854EbAT2q2FHKtCJ6rQ.png" /></figure><p>The model becomes the orchestrator, planner, router, and execution engine all at once.</p><p>While building AI applications over the past years, I started wondering if this was the right way to think about the problem.</p><blockquote>What if the LLM was not the center of the system?</blockquote><blockquote>What if it was simply one of several core components?</blockquote><h3><strong>The CPU Analogy</strong></h3><p>In a traditional computer system, the CPU performs computation. But the CPU is not the entire computer.</p><p>A complete system also needs:</p><ul><li>Memory</li><li>Storage</li><li>Input and Output</li><li>Device Drivers</li><li>Running Programs</li><li>An Operating System</li></ul><p>The operating system coordinates everything and allows programs to execute using those resources.</p><p>This led me to a simple thought:</p><blockquote>What if an LLM is just one component of an AI system, much like a CPU is just one component of a computer?</blockquote><p>The model performs <strong>reasoning</strong> and <strong>generation</strong>.</p><p>But an AI system also needs:</p><ul><li>Knowledge retrieval</li><li>State management</li><li>Tool execution</li><li>External integrations</li><li>Workflow orchestration</li></ul><p>These should not be the responsibilities of the model itself. There needs to be a <strong>runtime</strong> that is responsible for this.</p><h3><strong>Mapping AI Systems to Computer Systems</strong></h3><p>The analogy started becoming surprisingly useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*0bBlviMOkAqRkoZyHr7L9A.png" /><figcaption>Mapping AI systems to computer systems</figcaption></figure><p>Viewed through this lens, an AI application begins to look less like a <strong>prompt chain</strong> and more like a <strong>program</strong> executing over <strong>system resources.</strong></p><h3><strong>A Program-Centric View</strong></h3><p>Consider a simple <strong>Help Bot</strong>.</p><p>Most implementations are described as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*u5M45aQcwjooSQwfPahKKg.png" /></figure><p>But another way to describe the same thing is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*_WMM4rFBJueP-oF5LKjLwQ.png" /></figure><p>The <strong>program</strong> itself becomes the primary unit of execution, while the <strong>model</strong> becomes just <strong>one of several resources</strong> available to the <strong>runtime</strong>. It may also need to use other resources such as knowledge retrieval, tool execution, or state management.</p><p>This small shift in perspective has surprisingly large consequences.</p><h3><strong>Why A Runtime Is Needed</strong></h3><p>Once AI applications grow beyond a single prompt, they quickly require additional capabilities:</p><ul><li>Multiple models</li><li>Knowledge sources</li><li>State</li><li>Branching logic</li><li>External tools</li><li>Validation</li><li>Reusable workflows</li></ul><p>At that point, the challenge is no longer prompting.</p><p>The challenge is <strong>orchestration</strong>.</p><p>The system needs something responsible for:</p><ul><li>Managing execution state</li><li>Loading resources</li><li>Executing workflow steps</li><li>Handling inputs and outputs</li><li>Coordinating tools and models</li></ul><p>In other words: A <strong>runtime</strong>.</p><h3><strong>The Idea Behind GenOS</strong></h3><p>This realization eventually led me to build <strong>GenOS</strong>.</p><blockquote><strong>GenOS</strong> is a local-first runtime for AI systems.</blockquote><p>The goal of GenOS is not to be another prompt wrapper or agent framework. Instead, it explores what AI systems look like when they are treated as <strong>executable programs</strong> running over a collection of resources, rather than centering everything around the language model.</p><p>In <strong>GenOS</strong>, these executable programs are represented as <strong>Projects</strong>.</p><p>A GenOS <strong>Project</strong> defines:</p><ul><li>Inputs</li><li>Outputs</li><li>Workflow Graph</li><li>Entry Node</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YRaxfVaLo4nSszsT7DXkWQ.png" /><figcaption>GenOS Architecture</figcaption></figure><p>A <strong>Project</strong> can use <strong>resources</strong> such as:</p><ul><li>Models for inference/compute</li><li>Knowledge for storage</li><li>State for memory</li><li>Tools for external capabilities</li></ul><p>A <strong>Runtime Kernel</strong> coordinates these resources and executes <strong>Projects</strong>.</p><p>In this model, the <strong>Project</strong> becomes the primary unit of execution, while models, knowledge, tools, and state become resources that the Project uses while it runs.</p><h3><strong>Projects as Modules</strong></h3><p>One of the more interesting ideas that emerged during development was treating <strong>Projects</strong> as <strong>reusable execution units</strong>.</p><p>A <strong>Project</strong> can define <strong>Inputs</strong> &amp; <strong>Outputs </strong>and expose a workflow graph that other <strong>Projects</strong> can invoke as a <strong>Module</strong>.</p><p>This allows larger systems to be built from smaller reusable <strong>projects</strong>.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*P1yKDNpEtViRhC7wpV_p5A.png" /></figure><p>Each GenOS <strong>Project</strong> behaves like a program with a well-defined interface defined by its <strong>inputs</strong> and <strong>outputs</strong>, allowing complex systems to be composed from smaller, focused Projects.</p><h3><strong>Rethinking Agents</strong></h3><p>An unexpected outcome of this design was a different perspective on agents.</p><p>Many AI frameworks introduce agents as a special concept.</p><p>However, if <strong>Projects</strong> can invoke other <strong>Projects</strong>, then a sophisticated agent can simply be a <strong>higher-level project</strong> that coordinates other <strong>Projects</strong>.</p><p>In this model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*jy128IJ0BYSPDBLdVeCa4Q.png" /></figure><p>rather than a separate runtime abstraction.</p><p>This keeps the architecture simple while still supporting complex behavior.</p><h3><strong>Why This Matters</strong></h3><p>The AI ecosystem currently focuses heavily on models.</p><p>Models are important. But models are <strong>only one part</strong> of a complete AI system.</p><p>As applications become larger and more capable, concerns like:</p><ul><li>State</li><li>Knowledge</li><li>Tools</li><li>Reusability</li><li>Orchestration</li></ul><p>become increasingly important.</p><p>The question I wanted to explore was:</p><blockquote>What happens when we design <strong>AI systems</strong> the same way we design <strong>software systems</strong>?</blockquote><blockquote>Not around a single component, but around the interaction of many components coordinated by a runtime.</blockquote><h3><strong>Looking Ahead</strong></h3><p>GenOS is still in its early stages, but the idea continues to evolve.</p><p>The goal is to provide a <strong>structured environment</strong> in which language models can operate alongside knowledge, tools, state, and reusable workflows rather than being the center of the system.</p><p>Perhaps the most interesting realization from building GenOS has been this:</p><blockquote>The future of AI applications may not be about making the model responsible for everything.</blockquote><blockquote>It may be about building better runtimes around the model.</blockquote><p>Because a CPU alone is not a computer.</p><p>And an LLM alone is not an AI system.</p><h3><strong>Exploring the Idea</strong></h3><p><strong>GenOS</strong> is open source and still in its early stages, but it serves as a practical vehicle for exploring the ideas discussed in this article.</p><p>If you’re interested in runtime-oriented approaches to AI systems, I’d love to hear your thoughts, criticisms, and alternative perspectives.</p><p>Repository: <a href="https://github.com/sagenticlab/genos">https://github.com/sagenticlab/genos</a></p><p>npm: <a href="https://www.npmjs.com/package/@sagentic/genos">https://www.npmjs.com/package/@sagentic/genos</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df926f58bd0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Basic React Application from Scratch]]></title>
            <link>https://javascript.plainenglish.io/create-a-basic-react-application-from-scratch-888bff9564aa?source=rss-42f4f50cc853------2</link>
            <guid isPermaLink="false">https://medium.com/p/888bff9564aa</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Savinu Vijay]]></dc:creator>
            <pubDate>Mon, 27 Jun 2022 13:17:17 GMT</pubDate>
            <atom:updated>2022-06-27T13:17:17.021Z</atom:updated>
            <content:encoded><![CDATA[<h4>Without using create-react-app.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sJR53shvycUfn0LETAdA7A.jpeg" /></figure><p><a href="https://reactjs.org/">React</a> is currently the most popular component-based UI library/framework. The beauty of React is that complex UI patterns can be developed quickly with a minimum amount of code. The use of <a href="https://reactjs.org/docs/introducing-jsx.html">JSX</a> makes the development and integration of modular applications a breeze.</p><p>We can get started with a React application by using the create-react-app tool. But in this article, we try to create a React application manually by creating each file and filling its contents.</p><p>The reader is assumed to have a basic idea about <a href="https://nodejs.org/en/">Node.js</a> and is supposed to have Node and <a href="https://www.npmjs.com/">NPM</a> installed in their machines before we start.</p><p>We will be using <a href="https://code.visualstudio.com/">VS Code</a> tools to create and manage the files and folders. Let’s start by creating a base folder for the application and open it in VS Code.</p><h3>Creating the Files and Folders</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*ilLZINBsBtaldpf52epCEA.png" /></figure><p>Every React application contains a public folder, an src folder and a package.json file in its base folder.</p><p>We first create the package.json file for the application.</p><pre>{<br>    &quot;name&quot;: &quot;sample-app&quot;,<br>    &quot;version&quot;: &quot;0.0.1&quot;,<br>    &quot;private&quot;: true,<br>    &quot;dependencies&quot;: {<br>        &quot;react&quot;: &quot;18.1.0&quot;,<br>        &quot;react-dom&quot;: &quot;18.1.0&quot;<br>    },<br>    &quot;devDependencies&quot;: {<br>        &quot;react-scripts&quot;: &quot;latest&quot;<br>    },<br>    &quot;scripts&quot;: {<br>        &quot;start&quot;: &quot;react-scripts start&quot;,<br>        &quot;build&quot;: &quot;react-scripts build&quot;<br>    },<br>    &quot;browserslist&quot;: {<br>        &quot;development&quot;: [<br>            &quot;last 1 chrome version&quot;,<br>            &quot;last 1 firefox version&quot;,<br>            &quot;last 1 safari version&quot;<br>        ]<br>    }<br>}</pre><p>The dependencies include the latest version of react and react-dom libraries.</p><p>The devDependencies include the latest version of the react-scripts library. We also add two scripts to <strong>start </strong>and <strong>build </strong>the application. These are added to the scripts section of the package.json.</p><p>Finally, we set up the browser list for development. We include chrome, firefox and safari.</p><p>In the next step, we create public and src folders.</p><h4>The ‘public’ folder</h4><p>The public folder contains the index.html file and its associated files. In this example, we will be creating the index.html file only since this is a basic application.</p><p><strong>index.html</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>    &lt;head&gt;<br>        &lt;meta charset=&quot;UTF-8&quot;&gt;<br>        &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-   scale=1.0&quot;&gt;<br>        &lt;title&gt;Sample App&lt;/title&gt;<br>    &lt;/head&gt;<br>    &lt;body&gt;<br>        &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>The index file contains a basic HTML boilerplate. The body of the file contains a single &lt;div&gt; tag with id &quot;root&quot;. The whole application gets rendered within this &lt;div&gt;.</p><h4>The ‘src’ folder</h4><p>The src folder contains the major portion of the application code. It contains the index.js, style.css and App.js files. The index.js file forms the entry point to the React application. The App.js file is the base react component which is referenced in the index.js file. The style.css file contains the styles for the &#39;App&#39; component. This folder may also contain other react components and services. We only include the three main files in this example.</p><p><strong>index.js</strong></p><pre>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom&quot;;<br>import App from &quot;./App&quot;;</pre><pre>ReactDOM.render(&lt;App /&gt;, document.getElementById(&quot;root&quot;));</pre><p>React and ReactDOM libraries are initially imported into this file. Next, the App component which is the base component of the application is imported.</p><p>Now we render the App component into the root div element present in the index.html file using the ReactDOM.render() method.</p><p><strong>App.js</strong></p><pre>import React from &quot;react&quot;;<br>import &quot;./style.css&quot;;</pre><pre>export default function App() {<br>    return (<br>        &lt;div&gt;<br>            &lt;h1&gt;Hello from React!&lt;/h1&gt;<br>        &lt;/div&gt;<br>    );<br>}</pre><p>React library is initially imported followed by the style.css file. Then, we define the App component as a <a href="https://reactjs.org/docs/components-and-props.html#function-and-class-components"><strong>React function component</strong></a>. This is a JavaScript function which is exported as default from the App.js file. The App function returns a JSX element which defines the structure of this component. Here we return a div element containing an &lt;h1&gt; tag.</p><p>The style.css file is currently left empty. Styles may be added later as per requirement.</p><h3>Running the application</h3><p>Once we have all the files set up, it is time for &#39;npm install&#39;. Run the &#39;npm install&#39; command in the base folder of the application and wait for it to complete. It may complete with some warnings which may be ignored for the time being.</p><p>Once the installation is done, the node_modules folder and package-lock.json file would have been generated. Now, the folder structure may look as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*vPCKb8nkAeW5AodloDknbA.png" /></figure><p>We can launch the application using &#39;npm run start&#39;. This launches the created application in the default browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*yVS8PQZVfsttiLxXV1BdIg.png" /></figure><p>We can also build the application to the dist folder using ‘npm run build’ command.</p><blockquote>This approach can be a good way to get started with a React application from scratch and begin development. However, few additional files may be required in order to use this setup in production.</blockquote><h3>Conclusion</h3><p>In this article, we learned how to build a react application from scratch by creating all the associated files and folders manually. We saw the contents of each file in detail. We also saw how to build and run the application in a developer setup.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Check out our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Community Discord</em></strong></a><em> and join our </em><a href="https://inplainenglish.pallet.com/talent/welcome"><strong><em>Talent Collective</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=888bff9564aa" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/create-a-basic-react-application-from-scratch-888bff9564aa">Create a Basic React Application from Scratch</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create a To-Do List using JavaScript Web Components]]></title>
            <link>https://javascript.plainenglish.io/how-to-create-a-to-do-list-using-javascript-web-components-501306e68c8c?source=rss-42f4f50cc853------2</link>
            <guid isPermaLink="false">https://medium.com/p/501306e68c8c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-components]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Savinu Vijay]]></dc:creator>
            <pubDate>Tue, 24 May 2022 14:17:17 GMT</pubDate>
            <atom:updated>2022-05-24T14:17:17.097Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to create a To-Do List application using JavaScript Web Components and ES modules.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mbas2Wr3GRp9KnyR3Fudrg.jpeg" /></figure><p>A basic To-Do list application consists of a list of to-do items. New items can be added to the list and existing items can be deleted from the lists. We can edit an item and also mark it as checked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*6NmUej9BMN-dHapzb_ra5A.gif" /></figure><p>We use JavaScript <strong>Web Components</strong> to create a To-do List application with the above-mentioned features. We follow the component-based architecture explained in <a href="https://javascript.plainenglish.io/component-based-architecture-for-dynamic-html-websites-857c21f0c95a"><strong>this article</strong></a> for creating the To-do List application.</p><blockquote>Full Code for this project is available on <a href="https://github.com/savinuvijay/todo-list"><strong>GitHub</strong></a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/0*1ekI_cF2lqDzYx-H" /></figure><p>The contents of index.html and script.js are boilerplate code as described in the architecture. The style.css contains all the basic styles for the application.</p><h4><strong>AppModule</strong></h4><p>The AppModule contains the definition of the base component(app-root) and the todo-item component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LjHw_YWXhYjafMLevUAzlQ.png" /></figure><h4><strong>AppComponent</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*HqcB7sz57Mm0KaSR" /></figure><p>It starts with the definition of the AppTemplate. Here, we first import appComponent.css style and define the <strong>app-component</strong> body. The Body of the <strong>app-component</strong> consists of the <strong>page title</strong>, which is <em>‘Todo List’</em>, a <strong>div</strong> tag to hold a list of to-do items and finally a button to <strong>add(+)</strong> new to-do items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*unwcaj1AD2CJr4w93MXeVw.png" /></figure><p>We initialize the to-do list state to an empty array by calling TodoListDataService.initializeState() in the constructor of the AppComponent. We also set the todoList, todoItems and addTodoItemBtn variables to point to its respective HTML elements using querySelector().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WufwGZXDdchVoqFSEmpcww.png" /></figure><p>In the connectedCallback() we attach the addTodoItem() event handler to the addTodoItemBtn button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w1colvzatU1C361v8fzNJA.png" /></figure><p>The addTodoItem(e) method handles addTodoItemBtn <strong>[click]</strong>. It first creates a new todo-item component as an HTML element and its value is passed on to the newTodoItem variable. Then the todoIdCount variable is initialized to <strong>0</strong> if not yet initialized. Then todoIdCount is incremented by <strong>one</strong> and set as the newTodoItem.id. Finally, the newTodoItem is appended as a child to the todoItems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UklKRoNXiugV6u6KfsBZsg.png" /></figure><h4><strong>TodoItemComponent</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/0*ILE9clwd4OJ03WNK" /></figure><p>Firstly, we import the todoItemComponent.css <strong>style</strong> and define the todo-item <strong>template body</strong>. The todo-item template consists of a checkbox, todo-content and deleteTodoItem button.</p><p>A to-do item can be switched to <strong>editing mode</strong> by clicking on the <strong>content text</strong>. When clicked, the Todo content is switched to an <strong>input box</strong> containing the same text. The todo content can be edited in this mode. The edited content can be saved by clicking anywhere outside the todo item. This also switches the todo item back to <strong>display mode</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y0_JSTZamqqWGYyaDHe2Fw.png" /></figure><p>The constructor of the TodoItemComponent class initializes editingContent as <strong>false</strong> and mouseDownEl as <strong>null</strong>. These variables are used to handle toggling todo-content between <strong>edit</strong> and <strong>display</strong> modes.</p><p>We also set the todoItem, todoCheck, todoContent, contentInput, contentDisplay and deleteTodoItemBtn variables to point to its respective HTML elements using querySelector().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6-tiDAKQi03nGnOkinXfXg.png" /></figure><p>In the connectedCallback() method, contentInput and contentDisplay are initialized to &quot;Task &quot; + taskId. We also add the current todoItem to the store/database using the TodoListDataService.AddTodoItem(). Finally, we attach the <strong>event handlers</strong> to the listeners.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GPlfQLg--1Tr0WeK-7of4g.png" /></figure><h3><strong>Event Handler methods</strong></h3><h4><strong>todoItemClicked(e)</strong></h4><p>The todoItemClicked(e) method handles todoItem <strong>[mouseDown]</strong>. It sets the value of mouseDownEl as the click target. This saves the exact HTML element that was clicked to the mouseDownEl to be used later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RqpJ2dVYlDcjXLF_9uehUg.png" /></figure><h4><strong>documentClicked(e)</strong></h4><p>The documentClicked(e) method handles document <strong>[mouseDown]</strong>. After editing a todo item, when the user clicks anywhere outside, the edited content gets saved. This happens based on mouseDownEl.</p><p>When the user clicks anywhere in the document outside the todo item, the value of mouseDownEl will be <strong>null</strong>. When the user clicks inside a todo item, mouseDownEl gets a <strong>non-null</strong> value.</p><p>The value of the input box is saved as todo content when the value of mouseDownEl is <strong>null</strong> or anything other than content-input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XZhTj9XXzvhv5fGFxERp5A.png" /></figure><h4><strong>editContent(e)</strong></h4><p>The editContent(e) method handles contentDisplay <strong>[click]</strong>. The content of a todo item can be edited by clicking on it as mentioned above. When clicked, the editingContent flag is turned <strong>true</strong>, contentDisplay is made <strong>hidden </strong>and contentInput is made <strong>visible</strong>. Now the user can edit the todo item content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/0*oOOjG_wFUQ4uaHQO" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ogz_NuVtd600-x2a8DSs4g.png" /></figure><h4><strong>saveContent(e)</strong></h4><p>The saveContent(e) method is called within the documentClicked(e) event handler when the input content is to be saved. In this method, the editingContent flag is set to false as the first step. Next, the contentInput value is set as the contentDisplay <strong>innterHTML</strong>. Then, the contentInput is made hidden and contentDisplay is made visible. Finally, we update the todo item data using the todoItmeDataService.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6e6I4Ql9W1nXMHNQ1xnfnA.png" /></figure><h4><strong>deleteTodoItem(e)</strong></h4><p>The deleteTodoItem(e) method handles deleteTodoItemBtn <strong>[click]</strong>. When this button is clicked, if the current item has a valid parentNode and the parentNode is of class todo-items, then the current todo item is removed from todo-items using the removeChild() method. The todo item is deleted from the todo item data using the TodoListDataService before removing it from the parent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XXE_1D6dRnrH6aLgJzr8vw.png" /></figure><h4><strong>toggleChecked(e)</strong></h4><p>The toggleChecked(e) method handles todoCheck <strong>[click]</strong>. Here, the todo item checked status is updated in the todo item data using the TodoListDataService.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JZF6-buM3vBQNvwu4kupCQ.png" /></figure><h3><strong>TodoListDataService</strong></h3><p>The todoListDataService defines a static state array which holds the instantaneous state of the todo list and a set of static methods which may be used to manipulate the state. The Todo List state can be defined as follows.</p><pre>state = [<br>    {<br>        id: <strong>0</strong>,<br>        value: <strong>&quot;Task 0&quot;</strong>,<br>        checked: <strong>false</strong><br>    },<br>    {<br>        id: <strong>1</strong>,<br>        value: <strong>&quot;Task 1&quot;</strong>,<br>        checked: <strong>false</strong><br>    }<br>]</pre><p>It is an array of objects, where each object contains <strong>id</strong>, <strong>value</strong> and <strong>checked</strong>. The <strong>id</strong> is a number that holds the id of the todo item, <strong>value</strong> is a string that holds the todo item content and <strong>checked</strong> is a boolean that holds the checked status of the todo item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/0*TCkRvhYjZkohA44M" /></figure><h4><strong>Static Methods</strong></h4><p>The initilalizeState(state) method takes in the state array as argument and uses it to initialize the static state array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ZDIu4QPdbxi_hdEc2RxcQ.png" /></figure><p>The AddTodoItem(id, value, checked) method takes in <strong>id</strong>, <strong>value</strong> and <strong>checked</strong> status of a todo list item and pushes it into the state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t53kBL9iu-HfeBUkBQnYaQ.png" /></figure><p>The UpdateTodoItem(id, value) method takes in <strong>id</strong> and the updated <strong>value</strong>, finds the respective todoItem by id and updates its value to the new value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NItmrRp91P7Sc1qllhe7Ig.png" /></figure><p>The CheckTodoItem(id, checked) method takes in <strong>id</strong> and the new <strong>checked</strong> status, finds the respective todoItem by id and updates its checked status to the new one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4cZ4dSFOyzBI4qJyA9eLcQ.png" /></figure><p>The DeleteTodoItem(id) method takes in <strong>id</strong> and filters out the item by the id from the state array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FIE_2Ok0_t2BnsM_iG8ETw.png" /></figure><h3>Conclusion</h3><p>To wrap things up, we looked at how to create a To-Do list application using JavaScript Web Components. We followed the component-based architecture explained in <a href="https://javascript.plainenglish.io/component-based-architecture-for-dynamic-html-websites-857c21f0c95a"><strong>this article</strong></a> for creating the To-do List Application. We also implemented a data service that stores the state of the to-do list to an external source.</p><blockquote>Full Code for this project is available on <a href="https://github.com/savinuvijay/todo-list"><strong>GitHub</strong></a>.</blockquote><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Check out our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Community Discord</em></strong></a><em> and join our </em><a href="https://inplainenglish.pallet.com/talent/welcome"><strong><em>Talent Collective</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=501306e68c8c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-create-a-to-do-list-using-javascript-web-components-501306e68c8c">How to Create a To-Do List using JavaScript Web Components</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Component-based Architecture for Dynamic HTML Websites]]></title>
            <link>https://javascript.plainenglish.io/component-based-architecture-for-dynamic-html-websites-857c21f0c95a?source=rss-42f4f50cc853------2</link>
            <guid isPermaLink="false">https://medium.com/p/857c21f0c95a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-framework]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Savinu Vijay]]></dc:creator>
            <pubDate>Wed, 27 Apr 2022 13:17:22 GMT</pubDate>
            <atom:updated>2022-04-27T13:17:22.278Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using JavaScript Web Components</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QKf61O6ISz4qIjKc2S8kyg.jpeg" /></figure><p><a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components"><strong>Web Components</strong></a> allow us to create reusable custom HTML elements, with their functionality encapsulated away from the rest of the code. This can be combined with ES modules to create a component-based architecture for websites using HTML, CSS and vanilla JavaScript.</p><p>A <a href="https://en.wikipedia.org/wiki/Single-page_application"><strong>Single Page Application</strong></a> can be written without using any JavaScript frameworks or libraries by following this approach. This article helps you in understanding how this can be achieved.</p><blockquote>Full Code available on <a href="https://github.com/savinuvijay/single-page-app"><strong>GitHub</strong></a>.</blockquote><blockquote>Try out this architecture live on <a href="https://stackblitz.com/edit/web-platform-xxuyv2"><strong>StackBlitz</strong></a>.</blockquote><h3><strong>The Architecture</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/0*1EMbpXGYAeP8XeNP" /></figure><p>The application base folder consists of index.html, script.js and style.css. These three files mostly contain <a href="https://en.wikipedia.org/wiki/Boilerplate_code">boilerplate code</a> which can stay the same for any application made using this architecture. The base folder also contains an <strong>&#39;src&#39;</strong> folder that houses all the application-specific source code. This folder contains the AppModule, the AppComponent —<em> which is the base component</em>, all the child components and services. The AppModule and AppComponent are required files which form the entry point of customization. These files also contain some boilerplate code.</p><h3><strong>Exploring the Base Folder</strong></h3><p>The three files present in the base folder (index.html, script.js, style.css) form the starting point for the application.</p><h4><strong>Index.html</strong></h4><p>This is a boilerplate HTML file where the &lt;head&gt; section has the script.js file defined and style.css file linked. The script.js file is specified with type=&#39;module&#39; to enable ES modules. It is also marked &#39;defer&#39; in order to load it after the HTML loads.</p><p>The body of the index.html contains nothing but the reference to the &lt;app-root&gt;. This file is the only HTML file in the entire application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BBpfwFwIMv-iPtFZD2gdIw.png" /></figure><h4><strong>script.js</strong></h4><p>The script.js file contains the definition of the AppModule which forms the entry point to the rest of the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z_C-4URZsElfMwkeB5hCJQ.png" /></figure><p>The style.css file contains the overall styles for the application and is also linked to the index.html file.</p><h3><strong>Exploring the &#39;</strong><strong>src&#39; Folder</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/0*0KlLYbBd9WahUcO7" /></figure><p>The core part of the application exists in the <strong>src</strong> folder.</p><h4><strong>The Module</strong></h4><p>It starts with the appModule.js which is the only file referenced outside the ‘<strong>src’</strong> folder. It gets imported into the script.js file as shown above. The appModule.js contains an exported class named &#39;AppModule&#39; which contains the definition of the defineElements() method. This method gets called from the script.js file. All components present in the application including the base component and all the child components are defined in the body of this method.</p><p>In the below example, we see that the AppComponent is defined as app-root and the childOneComponent is defined as child-one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8flsamsShILwZuXFvmyD5w.png" /></figure><h4><strong>Components</strong></h4><p>Every component in this architecture comes in two parts. <strong>First</strong> is the JavaScript file which defines the HTML template and methods of the component. <strong>Second</strong> is the CSS file which defines the styles for the component and gets imported into the template.</p><p>The component JavaScript file consists of the HTML template definition and the component class definition. The component class is extended from the HTMLElement base class. This class defines a constructor and two life cycle methods of the Component. The connectedCallback() life cycle method is run as soon as the component is connected(Loaded) to the DOM and the disconnectedCallback() runs as soon as the component is disconnected(Removed) from the DOM.</p><h4><strong>The Base Component</strong></h4><p>The appComponent.js is a JavaScript Web Component which forms the base component of the application. This can be considered as a mandatory part of the architecture as it is the only component exposed externally to the index.html file as &lt;app-root&gt;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*htpMntAJXl5oY6HOG1MRdQ.png" /></figure><p>In the above example, the template of the appComponent contains a &lt;style&gt; tag which imports appComponent.css and a &lt;div&gt; tag which forms the body of the component. Within the component body, there is an &lt;h1&gt; tag with heading &#39;App Component&#39; and the &lt;child-one&gt; tag.</p><p>The AppComponent class contains the basic web component boilerplate code which is required for the application to run normally.</p><h4><strong>Child Components</strong></h4><p>Child components are placed inside the <strong>‘components’</strong> folder. All the child components that are created need to be defined in the AppModule and connected to the appComponent either directly or indirectly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hMF6DT0sybwOf8PNp1S5nw.png" /></figure><p>In the above example, the template of the childOneComponent contains a &lt;style&gt; tag which imports childOneComponent.css and a &lt;div&gt; tag which forms the body of the component. There is an &lt;h2&gt; tag with heading &#39;Child One&#39; within its body.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kAyoanwozzjzHjzlKL65kQ.png" /></figure><p>This application, when run, forms the above DOM structure. The &lt;app-root&gt; contains the body of the AppComponent within a <a href="https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot"><strong>Shadow Root</strong></a>. Similarly, the body of the &lt;child-one&gt; component is contained within a nested Shadow Root.</p><h4><strong>Services</strong></h4><p>Services are classes that contain a set of static functions which help the application interact with external services, APIs or Databases. These are used to isolate code which reference external resources, from the component. Services are placed inside the <strong>‘services’</strong> folder nested within the <strong>‘src’</strong> folder.</p><p>Services can be accessed from anywhere within the application. It needs to be imported into the respective file where it will be used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mZfVfycW7qqcR0ev6JzMeA.png" /></figure><p>The above example of a SampleDataService contains a static state array and two other static methods to manipulate the state. The addItem() method pushes an item into the state and the getItem() method gets an item from the state by id. These methods may be called from anywhere within the application.</p><pre>import { <strong>SampleDataService</strong> } from <strong>&quot;./services/SampleDataService.js&quot;</strong>;</pre><p>The SampleDataService is imported into the respective file where it will be used. If we want to add an item or two into the state after the AppComponent is loaded, we call SampleDataService.addItem() from the connectedCallback of the AppComponent.</p><pre>connectedCallback() {<br>    <strong>SampleDataService</strong>.addItem({ id: 1, value: “Item 1” });<br>    <strong>SampleDataService</strong>.addItem({ id: 2, value: “Item 2” });<br>}</pre><p>If we want to print a specific item to the console after the ChildOneComponent is loaded, we call SampleDataService.getItem(id) by passing the item id to it from the connectedCallback of the ChildOneComponent. We can then print the value to the console using console.log().</p><pre>connectedCallback() {<br>   let item = SampleDataService.getItem(1);<br>   console.log(&quot;Child One: &quot;, item);<br>}</pre><blockquote>The above approach of state management is not safe due to the mutable state variable. The <strong>state</strong> may be isolated from the services using the <strong>Redux</strong> pattern to improve safety.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7dOMqqBVdGLUG4BdmEmYRQ.png" /></figure><h3><strong>Conclusion</strong></h3><p>To wrap things up, we looked at how to create a Single Page Application using web components and JavaScript ES modules. We explored the architecture and folder structure created for this approach. We also explored all the files which are required as boilerplate for the application and saw how it can be customized.</p><p>The code for this architecture is available on <a href="https://github.com/savinuvijay/single-page-app"><strong>GitHub</strong></a>.</p><p>You can try out this architecture live on <a href="https://stackblitz.com/edit/web-platform-xxuyv2"><strong>StackBlitz</strong></a>.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=857c21f0c95a" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/component-based-architecture-for-dynamic-html-websites-857c21f0c95a">Component-based Architecture for Dynamic HTML Websites</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[6 Array Operations that Can Be Done with One JavaScript Function]]></title>
            <link>https://javascript.plainenglish.io/6-array-operations-that-can-be-done-with-one-javascript-function-c25f2a844a07?source=rss-42f4f50cc853------2</link>
            <guid isPermaLink="false">https://medium.com/p/c25f2a844a07</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Savinu Vijay]]></dc:creator>
            <pubDate>Tue, 01 Mar 2022 14:18:08 GMT</pubDate>
            <atom:updated>2022-03-01T14:18:08.973Z</atom:updated>
            <content:encoded><![CDATA[<h4>Array.Splice() — the one function that does it all.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ossBTZ8lBP2UlOxXWBPEQg.jpeg" /></figure><p>Arrays are the simplest and most widely used data structures in programming. Inserting or deleting the elements in an array are the most common operations that every programmer does on a day-to-day basis.</p><p>JavaScript arrays have a set of built-in functions which can be used to manipulate arrays. But one function among them can replace several other functions to perform some of the common array operations.</p><h3><strong>The Array.splice() function</strong></h3><p>The <strong>Array.splice(pos,k,item1,item2,...,itemN) </strong>function can be used to insert or delete any number of elements from any part of an array. The first argument specifies the <strong>position </strong>in the array at which an operation is to be performed. The second argument takes in the <strong>number of elements</strong> from that position to the right that may be deleted. The remaining arguments may be the items to be inserted at that position.</p><p>As the name suggests, this method cuts ✂ the array at position pos, deletes 🗑k elements from that position to the right ➡ and inserts 0 or more items at that position.</p><p>Consider the below figure. Here, the value of pos is taken as <strong>2</strong> and k is taken as <strong>3</strong>. The remaining arguments — which are the items to be inserted — are <strong>&quot;G&quot;</strong> and <strong>&quot;H&quot;</strong>.</p><pre>var arr = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;];<br>var pos = 2;<br>var k = 3;<br>var i1 = &quot;G&quot;;<br>var i2 = &quot;H&quot;;<br>arr.splice(pos, k, i1, i2);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TqFG-hpUimndrr2X" /></figure><p>When this method executes, the elements &quot;C&quot;,&quot;D&quot;,&quot;E&quot; will be removed and &quot;G&quot;,&quot;H&quot; will be inserted. This versatility of the splice() method enables it to be used to do the following array operations.</p><blockquote><strong><em>Note:</em></strong><em> The below array definition is used for all examples throughout this article.</em></blockquote><pre>var arr = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;];<br>console.log(arr); //  [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;]</pre><h3><strong>1. Inserting at the End</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4eHLctya-OVpEx4i" /></figure><p><strong>Array.push(item)</strong> is the default array method used to append one or more elements to the end of an array. But this can be done with <strong>splice()</strong> as follows.</p><pre>arr.splice(arr.length, 0, &quot;E&quot;);<br>console.log(arr); //  [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;]</pre><p>Here we set the first argument <em>(position)</em> as the <strong>length of the array</strong>, the second argument <em>(number of elements to be deleted)</em> as <strong>zero</strong> and the third argument as the <strong>element</strong> to be inserted.</p><p>Multiple elements cannot be inserted using <strong>Array.push()</strong>c method but can be done with splice() by passing those as comma-separated arguments to the end of the method.</p><pre>arr.splice(arr.length, 0, &quot;E&quot;, &quot;F&quot;);<br>console.log(arr); //  [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;]</pre><h3><strong>2. Deleting from the End</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WUxTauGem3ARtDuOqVNOFQ.png" /></figure><p>The <strong>Array.pop() </strong>is the default method used to delete an element from the end of an array. This can be done with <strong>splice()</strong> as follows.</p><pre>arr.splice(arr.length - 1);<br>console.log(arr); //  [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;]</pre><p>Here we set the first argument <em>(position)</em> as <strong>one less than the length of the array </strong>— the last element. The second argument need not be provided in this case because the method deletes all the elements from pos till the end of the array when the second argument is not available.</p><p>The <strong>Array.pop() </strong>can only delete one element at a time. But,<strong> </strong>multiple elements can be deleted from the end using the <strong>splice()</strong> method as follows. Here count specifies the number of elements to be deleted.</p><pre>var count = 2;<br>arr.splice(arr.length - count);<br>console.log(arr); //  [&quot;A&quot;, &quot;B&quot;]</pre><h3><strong>3. Inserting at the Beginning</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LJpQc3EdPrCDOzSEzPJO_w.png" /></figure><p>The <strong>Array.unshift(item)</strong> is the default method that can be used to insert an element at the beginning of an array. But this also can be done with <strong>splice()</strong> as follows.</p><pre>arr.splice(0, 0, &quot;E&quot;);<br>console.log(arr); //  [&quot;E&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;]</pre><p>Here we set both the first <em>(position)</em> and second arguments <em>(number of elements to be deleted)</em> as <strong>zero</strong> and the third argument as the <strong>element</strong> to be inserted.</p><p>Multiple elements can be inserted by passing those as comma-separated arguments at the end of the <strong>splice()</strong> method.</p><pre>arr.splice(0, 0, &quot;E&quot;, &quot;F&quot;);<br>console.log(arr); //  [&quot;E&quot;, &quot;F&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;]</pre><h3><strong>4. Deleting from the Beginning</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uUC4MayE8gVvba7GNvwC-A.png" /></figure><p>The <strong>Array.shift() </strong>is the default method used to delete an element from the beginning of an array. This can also be done using the <strong>splice()</strong> method as follows.</p><pre>arr.splice(0, 1);<br>console.log(arr); //  [&quot;B&quot;, &quot;C&quot;, &quot;D&quot;]</pre><p>Here we set the first argument <em>(position)</em> as <strong>zero</strong> and the second argument <em>(number of elements to be deleted)</em> as <strong>one</strong>.</p><p>The <strong>Array.shift() </strong>can only delete one element at a time. But,<strong> </strong>multiple elements can be deleted using the <strong>splice()</strong> method as follows. count is the number of elements to be deleted.</p><pre>var count = 2;<br>arr.splice(0, count);<br>console.log(arr); //  [&quot;C&quot;, &quot;D&quot;]</pre><h3><strong>5. Inserting in the Middle</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zrQUzx9cAwffORqwWJZjQQ.png" /></figure><p>There is no specific array method in JavaScript which can be used to insert elements in the middle of an array. However, there are several hacks through which this can be achieved. One among them is by using the <strong>splice()</strong> method.</p><pre>var pos = 2; // position where the element is to be added<br>arr.splice(pos, 0, &quot;E&quot;);<br>console.log(arr); //  [&quot;A&quot;, &quot;B&quot;, &quot;E&quot;, &quot;C&quot;, &quot;D&quot;]</pre><p>We initialize a variable pos that stores the position at which the element to be is inserted. Now, set the first argument <em>(position)</em> as <strong>pos</strong>, the second argument <em>(number of elements to be deleted)</em> as <strong>0</strong> and the third argument as the <strong>element </strong>to be inserted.</p><p>Multiple elements can be inserted in the middle by passing those as comma-separated arguments at the end of the splice method.</p><pre>var pos = 2; // position where the element is to be added<br>arr.splice(pos, 0, &quot;E&quot;, &quot;F&quot;);<br>console.log(arr); //  [&quot;A&quot;, &quot;B&quot;, &quot;E&quot;, &quot;F&quot;, &quot;C&quot;, &quot;D&quot;]</pre><h3><strong>6. Deleting from the middle</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yB72OdGdU9yuk_IJZwyDeQ.png" /></figure><p>The <strong>splice()</strong> method can also be used to delete an element from the middle of an array.</p><pre>var pos = 2;<br>arr.splice(pos,1);<br>console.log(arr); //  [&quot;A&quot;, &quot;B&quot;, &quot;D&quot;]</pre><p>We initialize a variable pos that stores the position at which the element to be is deleted. Now, set the first argument <em>(position)</em> as <strong>pos</strong> and the second argument <em>(number of elements to be deleted)</em> as <strong>one</strong>.</p><p>If count is the number of elements to be deleted, Multiple elements can be deleted by setting value of k as count</p><pre>var pos = 2;<br>var count = 2;<br>arr.splice(pos,count);<br>console.log(arr); //  [&quot;A&quot;, &quot;B&quot;]</pre><p>In this article, we learned about the <strong>Array.splice()</strong> function and how it may be used to replace several other functions in JavaScript.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c25f2a844a07" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/6-array-operations-that-can-be-done-with-one-javascript-function-c25f2a844a07">6 Array Operations that Can Be Done with One JavaScript Function</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Nested Comment/Reply Box Using JavaScript Web Components]]></title>
            <link>https://javascript.plainenglish.io/create-a-nested-comment-reply-box-using-javascript-web-components-d997c1198cc4?source=rss-42f4f50cc853------2</link>
            <guid isPermaLink="false">https://medium.com/p/d997c1198cc4</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Savinu Vijay]]></dc:creator>
            <pubDate>Mon, 07 Feb 2022 09:17:22 GMT</pubDate>
            <atom:updated>2022-02-07T09:17:22.474Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to create custom<strong> Web Components</strong> and use them along with <strong>JavaScript ES modules</strong>.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mWxNWRT0h5fUGV8dRAchCQ.jpeg" /></figure><p><a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components">Web Components</a> allow us to create reusable custom elements, with their functionality encapsulated away from the rest of the code. Here we create a custom comment-box web component and use it to build a <strong>Nested Comment/Reply system</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*o1GtPiy5VT4ceErioGTVzg.gif" /><figcaption>Nested Comment Reply box Demo</figcaption></figure><p>This article can help you in understanding how <strong>Web Components</strong> work and how they can be used along with JavaScript <strong>ES modules</strong>.</p><p>The full code for this project is available on <a href="https://github.com/savinuvijay/nested-comments"><strong>GitHub</strong></a>.</p><p>Live demo on <a href="https://stackblitz.com/edit/web-platform-nac3d2"><strong>StackBlitz</strong></a>.</p><h3>How it works</h3><p>The <strong>comment-box</strong> is defined as a JavaScript web component. It is defined in its separate JavaScript file which is commentBox.js. The styles for this component are defined in the commentBoxStyle.css file.</p><h4><strong>commentBox.js</strong></h4><p>We create a new HTML template element to begin with, and define the structure of the Web Component within its innerHTML. The style for the component is also linked within the innerHTML.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xrfMJ4UQoHlSMPZ-uteH-A.png" /></figure><p>The comment box consists of two parts. First, is the comment-edit-box, which consists of the comment input field and submit button. Second, is the comment-display-box, which displays the submitted comment, its author details, number of likes for that comment (initially 0) and the like &amp; reply buttons. It also contains a reply-box div which is invisible. The nested comment boxes for replies attach to this div, when the reply button is clicked.</p><p>Users may add any number of replies to a comment. But the level of nested replies is limited to 3. The nestingLimit is used to handle this and may be changed according to requirement.</p><pre>const nestingLimit = 3;</pre><p>Now we define the Web Component by creating a JavaScript class named CommentBox which extends HTMLElement. It is exported as an ES Module as well. We define the Web Component’s constructor and two life-cycle methods within this class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cs_EUyYPb1g45p_TguXykg.png" /></figure><p>The connectedCallback() life-cycle method is run as soon as the component is connected(Loaded) to the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction">DOM</a> and the disconnectedCallback() runs as soon as the component is disconnected(Removed) from the DOM. This class also contains several <strong>Event Handler Functions</strong> which will be explained in detail, later in the article.</p><h4><strong>Constructor()</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLKP-EPzj4qe1C8dj-QzJA.png" /></figure><p>The comment-box web component may take in a level attribute.</p><pre>&lt;comment-box <strong>level=&quot;0&quot;</strong>&gt;&lt;/comment-box&gt;</pre><p>This attribute specifies the level at which that particular comment box is nested. It is captured and stored in the this.level variable of the CommentBox class.</p><p>The value of the level is defaulted to <strong>zero</strong> when the level attribute does not exist in the HTML file. We also set the initial likeCount to <strong>zero</strong> in the constructor. Next, we attach a <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM">shadow DOM</a> to the element and append the template defined above as its child.</p><p>Finally, we set the commentEdit and commentDisplay variables to point to its respective HTML elements using querySelector() on the shadowRoot.</p><h4><strong>ConnectedCallback()</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BReZlXQmG5COzKZzMWiewQ.png" /></figure><p>The connectedCallback() method executes as soon as the Web Component is attached to the DOM. We attach the event listeners for all the buttons present on the component in this method.</p><p>The commentSubmit() event handler is attached to the submit-btn button and the commentLike() event handler is attached to the like-btn. The commentReply() event handler is attached to the reply-btn only when the current level is <strong>less than</strong> the nestingLimit. The reply-btn is <strong>disabled</strong> otherwise.</p><p>Finally, we set the display style for the commentDisplay element to <strong>none</strong>, as it will be initially hidden from view and will be displayed only when the comment is submitted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*8b25UcLLlVTC6p4Z0eAgTw.png" /></figure><h4><strong>DisconnectedCallback()</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8CWY4dfDUnvgGL5NimybBA.png" /></figure><p>The disconnectedCallback() is executed when the component is disconnected from the DOM. Here we remove all the event listeners that were attached while the component was created.</p><h3><strong>Event Listener Functions</strong></h3><h4><strong>CommentSubmit()</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ADL4DK-QalfHDM8DX2BM3Q.png" /></figure><p>The commentSubmit() method is called when the user types in a comment in the input box and clicks the <strong>submit button</strong>.</p><p>We first make the commentInput variable to point to the <strong>input box</strong> HTML element present within the commentEdit div. We also set the comment variable to point to the div in which the comment will be displayed and author variable to point to the <strong>author</strong> &lt;p&gt;tag.</p><p>Now, we set the comment submitted by the user as the content for display. This is done by setting the innerHTML of the <strong>comment</strong> div as the value of the commentInput. We also set the <strong>author</strong> name with the value from the sessionStorage.</p><p>Finally, we need to hide the commentEdit div and show the commentDisplay div. This is done by setting the <strong>display</strong> style for the commentEdit div to &#39;none&#39;, which hides it and commentDisplay div to &#39;block&#39; which displays it.</p><h4><strong>Comment like()</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PXmjatx2uFe2PKEuyjM3cA.png" /></figure><p>The commentLike() method is called when the user clicks on the <strong>Like button</strong> present beside any comment. The likes variable is set to point to the <strong>likes</strong> &lt;p&gt; tag using the querySelector. Then the likeCount is incremented and the innerHTML for the &lt;p&gt; tag is updated with the new <strong>likes count</strong>.</p><h4><strong>Comment Reply()</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iWjavg_5k7DeKDQbVNjLTA.png" /></figure><p>The commentReply() method is called when the user clicks on the <strong>Reply button</strong> beside any comment. We first make the replyBox variable to point to the reply-box div. This is the div to which all the <strong>comment replies</strong> will be added as children.</p><p>Then, a new comment-box component is created as an HTML element and its value is set to the newCommentBox variable. The <strong>level</strong> variable is incremented and its new value is set as an attribute for the newCommentBox. If the reply box already has any child nodes, then the newCommentBox is inserted <strong>before</strong> the <strong>first child</strong> in the reply-box, else the newCommentBox is appended directly as the first child. This is to ensure that the newer replies always appear on top.</p><h4><strong>Script.js</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rsC6uf-515rfZLFIznRQCA.png" /></figure><p>The CommentBox class is imported from commentBox.js as an <strong>ES module</strong>. We first set the current user data into the <strong>session storage</strong>. Then we define the CommentBox class as a custom element or a Web Component. We also set the custom HTML tag for this element as &#39;comment-box&#39;.</p><p><strong>Note: </strong>script.js file should be specified in the index.html with type=&#39;module&#39; to enable ES modules.</p><pre>&lt;script defer <strong>type=&quot;module&quot;</strong> src=&quot;script.js&quot;&gt;&lt;/script&gt;</pre><h4><strong>Index.html</strong></h4><p>The body of the index.html file is quite simple. It consists of a container and a comments div nested within it. These are used to center-align the comment section within the view-port at a specific width. Inside this div, we add the comment-box element which is the Web Component we have been creating so far. A level attribute is also added with value <strong>0</strong>, marking it the <strong>initial level</strong> of the comment box. This allows four levels of comments to be nested starting from zero. If the initial level is set as <strong>1</strong>, three levels of comments may be nested. If the <strong>level</strong> attribute is not specified initially, its value is defaulted to <strong>zero</strong> making three levels of nested replies possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5FQ36USDJLQ8PwcR2xQ6Mw.png" /></figure><h4><strong>Conclusion:</strong></h4><p>To wrap things up, we looked at how to create custom<strong> Web Components</strong> and use them along with <strong>JavaScript ES modules</strong>. This was done by creating a custom comment-box web component and using it to create a nested comment/reply system. We also saw the code for the web component, its life-cycle methods, and its associated event handles in detail.</p><p>The full code for this project is available on <a href="https://github.com/savinuvijay/nested-comments"><strong>GitHub</strong></a>.</p><p>Take a look at the live demo on <a href="https://stackblitz.com/edit/web-platform-nac3d2"><strong>StackBlitz</strong></a>.</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d997c1198cc4" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/create-a-nested-comment-reply-box-using-javascript-web-components-d997c1198cc4">Create a Nested Comment/Reply Box Using JavaScript Web Components</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type of Scopes in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/type-of-scopes-in-javascript-e717571721a2?source=rss-42f4f50cc853------2</link>
            <guid isPermaLink="false">https://medium.com/p/e717571721a2</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Savinu Vijay]]></dc:creator>
            <pubDate>Mon, 03 Jan 2022 05:18:36 GMT</pubDate>
            <atom:updated>2022-01-03T05:18:36.469Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0SBFNjCA0Bq4854MObDCbQ.png" /></figure><p>This article is intended for JavaScript developers who are trying to dive deeper into the Language. Knowing the following topics will be beneficial before you start reading.</p><ul><li><a href="https://en.wikipedia.org/wiki/JavaScript_engine">JavaScript Engine</a></li><li><a href="https://hellocode.dev/execution-context-in-javascript/">Execution Context (EC)</a></li><li><a href="https://www.javascripttutorial.net/javascript-call-stack/">Call Stack</a></li><li>Scopes and Variables in general</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*-U_VH6jELWdQGkwnvXsL3g.png" /></figure><p>JavaScript code runs within an <strong>Execution Context (EC). </strong>The <strong>Execution Contexts</strong> get pushed onto the call stack while the code executes. Every JavaScript program has a <strong>Global Execution Context</strong> which gets pushed when its execution begins. Whenever a function call is encountered, a new Execution Context is created for that specific function and is pushed onto the call stack.</p><p>The image shows the snapshot of call stack when <strong>line 7 </strong>of the below code is executing.</p><pre>1  var a0 = 0;<br>2  function testFunc() {<br>3      var a1 = 10;<br>4      testFunc1();<br>5      function testFunc1(){<br>6          var a2 = 20;<br><strong>7          console.log(a0,a1,a2);</strong><br>8      }<br>9  }<br>10 testFunc();<br>11 console.lob(a0);</pre><p>It shows the <strong>Global Execution Context(GEC)</strong> at the bottom and the Execution Contexts of the two nested functions above it.</p><h3><strong>Lexical Environment</strong></h3><p>A <strong>Lexical Environment(LE)</strong> gets created as part of each Execution Context. It consists of the local memory of that Execution Context along with the Lexical Environment of its immediate parent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*LvKeqi9ZfueC10KCQZoRYA.png" /></figure><p>During the execution of JavaScript code, the call stack may have several Execution Contexts stacked one above the other, with Global Execution Context(GEC) at the bottom of the stack.</p><blockquote>The <strong>Lexical Environment</strong> of the top most <strong>Execution Context</strong> has a reference to the <strong>EC</strong> of its <strong>parent</strong>(EC right below it).</blockquote><p>This is the same for all the ECs below it as well except for GEC which points to <strong>Null</strong>. This chain of Lexical Environments is called the <strong>Scope Chain</strong>.</p><h3><strong>Type of Scopes</strong></h3><p>The Lexical Environment or Scope of an Execution Context may contain the following different types of scopes.</p><p><strong>1. Global: </strong>🌏</p><p>Variables declared using the var keyword outside all functions in a JavaScript file become part of the <strong>Global Scope</strong>. It becomes the root of the JavaScript scope chain. Variables stored here will be accessible anywhere in the file. This is by default, the window object in the browser and global object in NodeJS.</p><p>A variable can be added to the Global scope as follows:</p><pre>var a0 = 0;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*nN6DDSrMnNBOOsooDCpaqw.png" /><figcaption>Status of Call Stack</figcaption></figure><p><strong>2. Script: </strong>📜</p><p>Variables declared using let or const keywords outside all blocks and functions in a JavaScript file become part of the <strong>Script Scope</strong>. It is similar to Global scope, but without any variables declared as var. It appears immediately after the global scope in the scope chain. Variables stored here will also be accessible anywhere in the file.</p><p>A variable can be added to the Global scope as follows:</p><pre>let b0 = 0;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*0GpEvNMNRHqV5JHlaRj_GA.png" /></figure><p><strong>3. Block: </strong>🧱</p><p>Variables declared using the let or const keywords within a JavaScript block <strong>{}</strong> become part of that <strong>block’s scope</strong>. (Note: any variables declared using var keyword within a block are moved to its parent scope (global / function / closure)) by the JavaScript Engine. A block can appear anywhere in a JavaScript file. It may be declared inside or outside functions. It can also be nested within other blocks. Hence, it gets added to the scope chain wherever it is encountered in the code. Variables stored here will only be accessible within that particular block.</p><p>A variable can be added to the block scope as follows:</p><pre>{<br>    var a1 = 10;<br>    let b1 = 10;<br>}</pre><p>Please note that a1 is moved to the Global scope even though it was declared within the block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*7wg8xaR1FiT57WkFqQGx0A.png" /></figure><p><strong>4. Local (Function): </strong>🏡</p><p>Variables declared inside a function become part of its <strong>Local Function Scope</strong>. Variables declared using any of the variables type (var/let/const) can appear here. This gets added to the Execution Context for that function once it gets pushed onto the call stack. Variables stored here are only accessible within that function.</p><p>A variable can be added to the local scope as follows:</p><pre>function testFunc(){<br>    var a2 = 20;<br>    let b2 = 20;<br>}<br>testFunc();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*1K8d_xjLCH1i0KULIeQfmQ.png" /></figure><p><strong>5. Closure: </strong>📦</p><p>When a function is defined within another function, the variables that are present in the Local Environment of the parent function, become the <strong>Closure</strong> for the new function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*Ok1bjni-QjAoYMsBwecK9w.png" /></figure><p>The variables in the local environment of the parent function which are marked as <strong>‘local’</strong> are now marked as <strong>‘closure’ </strong>when it becomes part of the new function.</p><p>Variables declared using var, let and const can appear here. This gets attached to the top of the scope chain just before the local scope of that function get attached.</p><pre>function testFunc() {<br>    var a2 = 20;<br>    let b2 = 20;<br>    function testFunc1() {<br>        var a3 = 30;<br>        let b3 = 30;<br>    }<br>    testFunc1();<br>}<br>testFunc();</pre><h3><strong>Forming the Scope Chain:</strong></h3><p>The global scope is added to the lexical environment of the <strong>global execution context</strong> by default. It gets added even when the JavaScript file is totally empty.</p><pre>1 var a0 = 0;</pre><p>Consider the above code. a0 gets added to the global scope since it is a variable of type var which is declared globally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*H_-z1Nmr_78MH4E1EYjLkA.png" /></figure><p>The LE of GEC may also contain script and block scopes. The <strong>script</strong> scopes get added if there are any let or const variables declared globally as shown below.</p><pre>1 var a0 = 0;<br>2 let b0 = 0;<br>3 const c0 = 0;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*RN9OxCDVz_ji-zHnSAFn9Q.png" /></figure><p>The <strong>block</strong> scopes get added to GEC if there are any blocks declared globally.</p><pre>1 var a0 = 0;<br>2 let b0 = 0;<br>3 const c0 = 0;<br>4 {<br>5    var a1 = 10;<br>6    let b1 = 10;<br>7    const c1 = 10;<br>8 }<br>9</pre><p>A block scope gets added to the lexical environment only when it is encountered during execution. In the above example, block scope gets added while executing line 5 to 7. It gets removed from the scope once the execution comes out of that block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UJ7iE-f_nnt-VKu79wbraA.png" /></figure><p>The above image shows the snapshot of the call stack during the execution of <strong>line 3</strong>, <strong>line 7</strong> and <strong>line 9</strong>. Please note that a1 becomes part of the global scope even when declared within a block. Also, a1 was present in the global scope from the beginning.</p><h3><strong>Functions and Scopes</strong></h3><h4><strong>Global Functions</strong></h4><p>If a function is declared globally, its Lexical Environment consists of the <strong>Lexical Environment of GEC </strong>along with its <strong>Local Environment</strong>.</p><pre>1 var a0 = 0;<br>2 let b0 = 0;<br>3 const c0 = 0;<br>4 function testFunc() {<br>5    var a1 = 10;<br>6    let b1 = 10;<br>7    const c1 = 10;<br>8 }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*7GlmlpfV9xgqtPaCd2LTbA.png" /></figure><h4>Nested Functions</h4><p>If the function is nested within other functions, then its lexical environment contains</p><ul><li>Lexical Environment of Grandparent</li><li>Local Environment of Parent as Closure</li><li>Local Environment of itself</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQJklTCbkez5mSFd-CJVZw.png" /></figure><p>The following code demonstrates how functions are nested within other functions.</p><pre>1 var a0 = 0;<br>2 let b0 = 0;<br>3 function testFunc() {<br>4    var a1 = 10;<br>5    let b1 = 10;<br>6    function testFunc1() {<br>7        var a2 = 20;<br>8        let b2 = 20;<br>9    }<br>10}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RORrlZS1AtVelmtlq9X-RQ.png" /></figure><p>Variables in the Closure of a function are bundled together along with it. These values will be retained even when the Execution Context of its parent function no longer exists in the call stack. Consider the below example.</p><pre>1  function testFunc() {<br>2    var a2 = 20;<br>3    let b2 = 20;<br>4    console.log(a2, b2);<br>5    function testFunc1() {<br>6        var a3 = 30;<br>7        let b3 = 30;<br>8        console.log(a2, a3, b2, b3);<br>9    }<br>10    return testFunc1;<br>11 }<br>12 var testFunc1 = testFunc();<br>13 testFunc1();</pre><p>Here, the testFunc1() which is defined inside testFunc() is not called within the function but, returned from it. We get testFunc1() returned from testFunc() at <strong>line 12 </strong>and it is called at <strong>line 13</strong>. At this point, the call stack only contains GEC and EC of testFunc1(). But the Lexical Environment of testFunc1() will have a2 and b2 which was part of testFunc(), defined within its Closure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*OJgWax6W9yYPt25g89jhkA.png" /></figure><h4>Function containing Blocks</h4><p>A function may also contain Blocks within it. If so, the local environment of a function may contain Blocks. If the current function exists inside a block (of nested blocks) within its parent, then there will be a Block scope(s) attached to its Closure.</p><pre>var a0 = 0;<br>let b0 = 0;<br>function testFunc() {<br>    var a1 = 10;<br>    let b1 = 10;<br>    {<br>        var a2 = 20;<br>        let b2 = 20;<br>        function testFunc1() {<br>            var a3 = 30;<br>            let b3 = 30;<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKU3j7vLVXYC9wOAFHoHyw.png" /></figure><h4>Function is nested within multiple levels</h4><p>If the function is nested within multiple levels, it’s Closure will form a chain of Closures of its parent functions. The below code contains several different possibilities for all the different types of scopes discussed so far.</p><pre>1 var a0 = 0;<br>2 let b0 = 0;<br>3 function testFunc() {<br>4    var a1 = 10;<br>5    let b1 = 10;<br>6    console.log(a0, a1, b0, b1);<br>7    {<br>8        var a2 = 20;<br>9        let b2 = 20;<br>10       console.log(a0, a1, a2, b0, b1, b2);<br>11       function testFunc1() {<br>12          var a3 = 30;<br>13          let b3 = 30;<br>14          console.log(a0, a1, a2, a3, b0, b1, b2, b3);<br>15          function testFunc2() {<br>16              var a4 = 40;<br>17              let b4 = 40;<br>18              console.log(a0, a1, a2, a3, a4, b0, b1, b2, b3, b4);<br>19              {<br>20                  var a5 = 50;<br>21                  let b5 = 50;<br>22                  console.log(a0, a1, a2, a3, a4, a5, <br>23                              b0, b1, b2, b3, b4, b5);<br>24              }<br>25          }<br>26          testFunc2();<br>27      }<br>28      testFunc1();<br>29   }<br>30}<br>31testFunc();</pre><p>The snapshot of the call stack while executing <strong>line 22</strong> of the above code is given below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GzW7zyJsSwZAY9z0O0WlEQ.png" /></figure><p>When the above code is executed in the browser, the Scope tab while executing <strong>line 22</strong> looks as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*xQ8xKi0UeKR1huWE3kX6Pg.png" /></figure><h3><strong>Conclusion</strong></h3><p>This article was about lexical environments, scope chaining and different types of Scopes in JavaScript. We also discussed how the scope behaves, and how the scope chain is formed in a variety of code scenarios.</p><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><em>free weekly newsletter</em></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><em>community Discord</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e717571721a2" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/type-of-scopes-in-javascript-e717571721a2">Type of Scopes in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous JavaScript: The Restaurant Analogy]]></title>
            <link>https://javascript.plainenglish.io/asynchronous-javascript-the-restaurant-analogy-55c38d0517e0?source=rss-42f4f50cc853------2</link>
            <guid isPermaLink="false">https://medium.com/p/55c38d0517e0</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Savinu Vijay]]></dc:creator>
            <pubDate>Thu, 02 Dec 2021 14:51:21 GMT</pubDate>
            <atom:updated>2021-12-02T14:51:21.987Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Asynchronous JavaScript — The Restaurant Analogy" src="https://cdn-images-1.medium.com/max/1024/1*5_XNuJjxdJUgr5bQ_fyAnA.png" /></figure><p>This article is intended for beginners who are starting off with JavaScript and trying to understand the working of JavaScript Runtime. This will be a good refresher for experienced professionals as well.</p><p>This is my humble attempt to oversimplify the asynchronous nature of JavaScript using the <strong>Restaurant Analogy</strong>. Feel free to correct me in the comments if I have made any mistakes.</p><h3><strong>Need For Asynchronous Execution</strong></h3><p>JavaScript is a synchronous, single-threaded programming language. Its code is executed sequentially using a single call stack within a single thread. But it is not possible to do all operations sequentially.</p><p>Suppose we want to wait for some data or input to be generated during a sequential run. Since JavaScript is single-threaded, making the code wait on some operation may result in freezing the whole application. These kinds of scenarios can be avoided by offloading such time-consuming operations from the main thread. <strong>JavaScript Runtime Environments</strong>(Browsers/NodeJS) provide a set of external APIs for handling such operations.</p><figure><img alt="JavaScript Runtime Environment" src="https://cdn-images-1.medium.com/max/883/1*1tg1-yOFeIzXHzh5ZOS7XQ.png" /></figure><p>The above image shows the basic architecture of the JavaScript Runtime Environment. It includes the following parts:</p><ul><li><a href="https://en.wikipedia.org/wiki/JavaScript_engine">JavaScript Engine</a> ⚙️</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API">Web APIs</a> 🔴🔴🔴</li><li>Task Queue 🟦🔣🔠🔢🔡🔤</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop">Event Loop</a> 🔄</li></ul><p>All these elements form the basic building blocks of Asynchronous JavaScript.</p><h3><strong>If Web Browser was a Restaurant</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p4okYjP7ctBU-M1uEEsiQA.png" /><figcaption>* the waiter is part of the JS Runtime even though shown outside</figcaption></figure><p>Consider the web browser as a <strong>Restaurant</strong>. It consists of a dining hall and a kitchen.</p><p>The <strong>Dining Hall</strong> is the place where customers come in and place orders. This is analogous to a user loading a <strong>Web Page </strong>and performing some operation like fetching data from the server.</p><p>The<strong> Kitchen</strong> is the place where all the magic happens. This is analogous to the <strong>JavaScript Runtime Environment </strong>which consists of different components, each performing a separate task.</p><p>These components are listed below.</p><blockquote><em>🤵</em><strong><em>Waiter(JavaScript Engine)</em></strong>: The waiter performs the task of running around taking orders and submitting it to the kitchen, serving food and arranging the tables. The waiter is also part of the kitchen even though he is shown outside in the figure. This is analogous to the <strong>JavaScript Engine</strong> that runs the code.</blockquote><blockquote><em>👨‍🍳</em><strong><em>Chefs(Web APIs)</em></strong>: The chefs take the order from the waiter, prepare the item and put it down on the delivery desk. This is analogous to the <strong>Web APIs </strong>performing the task requested by the user and pushes the result to the task queue.</blockquote><blockquote><em>👨‍💼</em><strong><em>Take-Away Manager(Event Loop)</em></strong>: His job is to manage the takeaway counter. He performs two main tasks repeatedly.</blockquote><blockquote>1. Check if there are items on the delivery desk.</blockquote><blockquote>2. Check the availability of the waiter and call him whenever he is free.</blockquote><blockquote>This is analogous to the <strong>Event Loop </strong>whose job is to:</blockquote><blockquote>1. Check if there are items in the Task Queue</blockquote><blockquote>2. Check the status of the call stack within the JavaScript Engine and push items from the queue if it is empty.</blockquote><blockquote><em>🍽️</em><strong><em>Delivery Desk(Task Queue)</em></strong>: This is the desk on which the chefs place the prepared dishes, so that the takeaway manager can pass it on to the waiter when available. This is analogous to the <strong>Task Queues</strong> present in the JavaScript Runtime.</blockquote><h4><strong>Placing an Order</strong></h4><p>Each order from a customer can be equated to an <strong>API call</strong>. When a customer makes an order, the <strong>waiter</strong>🤵 notes it down and passes it to the respective <strong>chef</strong>👨‍🍳 in the kitchen.</p><p>If the restaurant was working <strong>Synchronously</strong>, the <strong>waiter</strong>🤵would be waiting in the kitchen until the order is done, so that it can be delivered to the customer.</p><p>This is a problem😑. While the food is being prepared, the dining hall operations of the restaurant will be halted🚫. There will be no new orders taken, no food served or no tables arranged.</p><p>This can be avoided if the restaurant is functioning in an<strong> Asynchronous</strong> manner.</p><p>The <strong>waiter</strong>🤵 now passes the order to the kitchen and continues with his tasks while the <strong>chef</strong>👨‍🍳 prepare the dish. Once the dish is prepared, the <strong>chef</strong>👨‍🍳 puts it down on the <strong>delivery desk</strong>🍽️. Now the <strong>Take-away manager</strong>👨‍💼 takes over and lets the <strong>waiter</strong>🤵 know that the particular <strong><em>order is ready</em></strong>. The <strong>waiter</strong>🤵 can then take the order and serve it to the customer.</p><p>As a result, the <strong>waiter</strong>🤵 and hence the dining hall operations, <strong>will not be blocked</strong> while the food is being prepared.</p><h4>Callbacks</h4><p>JavaScript handles such operations using <strong>Callbacks</strong>📞. When the order is passed to the kitchen, we also pass a <strong>callback</strong>📞<strong> </strong>along with it. This callback holds a <strong>note</strong>📝 saying <strong>&#39;Serve order to table X&#39;</strong>. When the order is ready the <strong>chef</strong>👨‍🍳 places the prepared dish along with the <strong>callback</strong> <strong>note</strong>📝 on the <strong>delivery desk</strong>🍽️. The <strong>Take-away manager</strong>👨‍💼 then makes a <strong>call</strong>📞 to the <strong>waiter</strong>🤵 for that particular order. The <strong>waiter</strong>🤵 receives the item, reads the <strong>note</strong>📝 and serves the item on <strong>table X</strong>.</p><h4><strong>Representing the restaurant functions through code</strong></h4><p>The following functions are responsible for fulfilling each order that comes in.</p><blockquote><strong><em>prepareItem(itemName, callback)</em></strong>: This function takes in an <strong><em>itemName</em></strong><em>🍔</em> and <strong>callback</strong><em>📞</em> as parameters. Preparing the item is simulated using the <strong>setTimeout</strong><em>⏰</em> API which fires after the specified <strong>timeout</strong><em>⏳</em>(Preparation Time). The preparation time is chosen using the <strong><em>itemName</em></strong> and the timeout is set based on it. Once the <strong>setTimeout</strong><em>⏰</em> fires, it calls the passed in callback function.</blockquote><pre>function prepareItem(itemName, callback){<br>    Let preparationTime = 0;<br>    switch(itemName){<br>        case &quot;coffee☕&quot;: preparationTime = 4000; break;<br>        case &quot;soda🥤&quot;: preparationTime = 2000; break;<br>        case &quot;frenchFries🍟&quot;: preparationTime = 5000; break;<br>        case &quot;hamburger🍔&quot;: preparationTime = 3000; break;<br>        case &quot;sandwich🥪&quot;: preparationTime = 6000; break;<br>        default: preparationTime = 1000;<br>    }<br>    setTimeout(()=&gt;{<br>        console.log(itemName + &#39;Prepared&#39;);<br>        callback();<br>    },preparationTime);<br>}</pre><pre>function serveOrder(){<br>    console.log(&#39;Order Served&#39;);<br>}</pre><blockquote><strong><em>serveOrder()</em>:</strong> This function prints <strong>&#39;Order Served&#39;</strong>on the <strong>console</strong> <em>💻</em>. It is supposed to be called once items in the order are done preparing.</blockquote><pre>function serveOrder(){<br>    console.log(&#39;Order Served&#39;);<br>}</pre><p>The <strong>prepareItem()</strong> function can now be called by passing <strong>&quot;coffee</strong>☕&quot; as the <strong>itemName</strong> and the <strong>serveOrder()</strong> method as <strong>callback (note </strong>📝<strong>)</strong></p><pre>prepareItem(&quot;coffee☕&quot;, serveOrder);</pre><p>This function call can be wrapped in a <strong>submitOrder()</strong> function for better modularity.</p><pre>function submitOrder(){<br>    prepareItem(&quot;coffee☕&quot;, serveOrder);<br>}<br>submitOrder();</pre><p>This works fine, but is not enough🤨. What if the customer makes an order that contains <strong>three related items.</strong></p><pre><strong>[&quot;hamburger</strong>🍔<strong>&quot;, &quot;frenchFries</strong>🍟<strong>&quot;, &quot;soda</strong>🥤<strong>&quot;]</strong></pre><p>Any one of these three items, if served separately, is useless. It needs to be served together. This now leads to a new problem🙄.</p><p>If the <strong>waiter</strong>🤵 places order for all the three items together, the<strong> submitOrder()</strong> function looks like this:</p><pre>function submitOrder(){<br>    prepareItem(<strong>&quot;</strong>hamburger🍔<strong>&quot;</strong>, serveOrder);<br>    prepareItem(&quot;frenchFries🍟&quot;, serveOrder);<br>    prepareItem(&quot;soda🥤&quot;, serveOrder);<br>}<br>submitOrder();</pre><p>This will not produce the desired results😕 as the items may arrive out of order.</p><h4>Nested Callbacks</h4><p>This issue can be resolved if <strong>nested callbacks</strong>📞📞📞 are used.</p><p>The <strong>waiter</strong>🤵 submits the order for <strong>&quot;hamburger</strong>🍔<strong>&quot;</strong> to the respective <strong>chef</strong>👨‍🍳 and passes a <strong>callback </strong>along with it having the following <strong>notes</strong>📝</p><pre><strong>* Submit Order for &quot;</strong><strong>frenchFries</strong>🍟<strong>&quot;</strong><br><strong>* Submit Order for </strong><strong>&quot;soda</strong>🥤<strong>&quot;</strong><br><strong>* Serve items to table X</strong></pre><p>Once the order gets completed, the <strong>chef</strong>👨‍🍳 places it onto the <strong>delivery desk</strong>🍽️ and the <strong>take-away manager</strong>👨‍💼 makes a <strong>call</strong>📞 for the <strong>waiter</strong>🤵 as usual.</p><p>The <strong>waiter</strong>🤵 removes the <strong>note</strong>📝 at the top, reads it and submits the order for the &quot;<strong>frenchFries</strong>🍟&quot; as per the note. The <strong>&quot;hamburger</strong>🍔<strong>&quot;</strong> is not delivered immediately. The order for &quot;<strong>frenchFries</strong>🍟&quot; is placed along with the remaining <strong>callback</strong> <strong>notes</strong>📝.</p><pre><strong>* Submit Order for </strong><strong>&quot;soda</strong>🥤<strong>&quot;</strong><br><strong>* Serve items to table X</strong></pre><p>Once the second order gets completed, the item arrives at the <strong>delivery desk </strong>🍽️<strong> </strong>and the <strong>waiter</strong>🤵 is <strong>called</strong>📞 again. Now, the <strong>waiter</strong>🤵 removes the <strong>note</strong>📝 at the top, reads it and submits the order for <strong>&quot;soda</strong>🥤<strong>&quot;</strong>. The <strong>&quot;hamburger</strong>🍔<strong>&quot; </strong>and &quot;<strong>frenchFries</strong>🍟&quot; are not delivered yet. This order is placed along with the last <strong>callback</strong> <strong>note</strong>📝.</p><pre><strong>* Serve items to table X</strong></pre><p>When the order gets completed, the item arrives at the <strong>delivery desk</strong>🍽️ and the <strong>waiter</strong>🤵 is <strong>called</strong>📞 once again. Now, the <strong>callback</strong> <strong>note</strong>📝 says to serve the order. Hence, he serves all the items on <strong>table X </strong>together.</p><p>The <strong>submitOrder()</strong> function using <strong>Nested Callbacks</strong> is as follows.</p><pre>function submitOrder(){<br>    prepareItem(<strong>&quot;</strong>hamburger🍔<strong>&quot;</strong>, ()=&gt;{<br>        prepareItem(&quot;frenchFries🍟&quot;, ()=&gt;{<br>            prepareItem(&quot;soda🥤&quot;, serveOrder);<br>        });<br>    });<br>}<br>submitOrder();</pre><figure><img alt="sequence diagram for nested callbacks" src="https://cdn-images-1.medium.com/max/1024/1*lcCQLMx5QvZeacvAAtT6_g.png" /></figure><p>The above sequence diagram shows the timing between orders for three different items.</p><p>This order of three items is itself quite overwhelming right?😅 What if we had a few more items. The <strong>submitOrder()</strong> function in this case may look somewhat like this😵.</p><pre>function submitOrder(){<br>    prepareItem(&quot;coffee☕&quot;, ()=&gt; {<br>        prepareItem(&quot;soda🥤&quot;, ()=&gt; {<br>            prepareItem(&quot;frenchFries🍟&quot;, ()=&gt; {<br>                prepareItem(&quot;hamburger🍔&quot;, ()=&gt; {<br>                    prepareItem(&quot;sandwitch🥪&quot;, serveOrder);<br>                });<br>            });<br>        });<br>    });<br>}<br>submitOrder();</pre><p>The readability of such code reduces after each nesting and becomes difficult to maintain. This kind of code is often referred to as <strong>‘The Callback Hell’</strong>👹.</p><h3><strong>Promises</strong></h3><p>The ES6 version of JavaScript introduced <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise"><strong>Promises</strong></a>🤝 to handle such issues. A <strong>Promise</strong> is an <strong>object</strong> representing the <strong>eventual completion or failure </strong>of an asynchronous operation.</p><p>While using <strong>promises</strong>, the <strong>waiter</strong>🤵 gets a <strong>promise</strong>🤝<strong> </strong>back when an order is placed. No callback note is passed to the kitchen in this case. The <strong>waiter</strong>🤵 then attaches a <strong>note</strong>📝 that says, <strong><em>what needs to be done when the promise is resolved</em></strong>, to the <strong>promise</strong>🤝 and keeps it with himself. In our example, the attached note will be:</p><pre><strong>* Serve item to table X</strong></pre><p>When the order is ready the <strong>chef</strong>👨‍🍳 places it on to the <strong>delivery desk</strong>🍽️ along with the <strong>&#39;Promise Resolved </strong>✅&#39; message.</p><p>The <strong>take-away manager</strong>👨‍💼 then hands over the order to the <strong>waiter</strong>🤵. He then finds the matching <strong>promise</strong>🤝 from his set of <strong>promises</strong>, reads the attached <strong>note</strong>📝 and serves the item on <strong>table X</strong>.</p><h4><strong>Promise code implementation</strong></h4><p>We can rewrite the <strong>prepareItem()</strong> function to return a <strong>promise</strong>🤝 as follows.</p><pre>function prepareItem(item){<br>    let preparationTime = 0;<br>    switch(item){<br>        case &quot;coffee☕&quot;: preparationTime = 4000; break;<br>        case &quot;soda🥤&quot;: preparationTime = 2000; break;<br>        case &quot;frenchFries🍟&quot;: preparationTime = 5000; break;<br>        case &quot;hamburger🍔&quot;: preparationTime = 3000; break;<br>        case &quot;sandwich🥪&quot;: preparationTime = 6000; break;<br>        default: preparationTime = 1000;<br>    }<br>    return new <strong>Promise</strong>((resolve, reject) =&gt; {<br>        setTimeout(()=&gt;{<br>            console.log(item + &#39;Prepared&#39;);<br>            resolve();<br>        },preparationTime);<br>    });<br>}</pre><p>The function no longer takes a <strong>callback</strong> function as the argument, but now returns a new <strong>Promise object</strong>. The promise takes an anonymous function having <strong>resolve</strong>✅ and <strong>reject</strong>❌ as arguments. Instead of calling a callback function, we can call <strong>resolve()</strong> if the operation is <strong><em>successful</em></strong> or <strong>reject()</strong> if there is an <strong><em>error</em></strong>.</p><p>Using the above implementation of <strong>prepareItem()</strong>, the<strong> submitOrder()</strong> function for a single item can be written as follows.</p><pre>function submitOrder(){<br>    let res = prepareItem(&quot;coffee☕&quot;);<br>    res.then(serveOrder);<br>}<br>submitOrder();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JL4iJVS5mLz9B4j1roMeOA.png" /><figcaption>Callbacks vs Promises</figcaption></figure><h4><strong>Promise chaining:</strong></h4><p><strong>Promise chaining </strong>🤝🔗🤝🔗🤝<strong> </strong>is a solution to the callback hell situation caused by nested callbacks.</p><p>The ‘<strong>then()</strong>’ call on a promise response takes a function as argument. This callback function may return another <strong>Promise</strong>🤝. The response of this new <strong>promise</strong>🤝 can be accessed by <a href="https://www.tutorialspoint.com/what-is-function-chaining-in-javascript">chaining</a> ⛓‘<strong>then()</strong>’ calls.</p><p>The <strong>submitOrder() </strong>function using a sequence of promises can look like this:</p><pre>function submitOrder() {<br>    let res1 = prepareItem(&quot;hamburger🍔&quot;);<br>    let res2 = res1.then(() =&gt; {<br>        return prepareItem(&quot;frenchFries🍟&quot;);<br>    });<br>    let res3 = res2.then(() =&gt; {<br>        return prepareItem(&quot;soda🥤&quot;); <br>    });<br>    res3.then(serveOrder);<br>}<br>submitOrder();</pre><p>This can be further simplified by removing the <strong>return</strong> keyword as follows:</p><pre>function submitOrder() {<br>    let res1 = prepareItem(&quot;hamburger🍔&quot;);<br>    let res2 = res1.then(() =&gt; prepareItem(&quot;frenchFries🍟&quot;));<br>    let res3 = res2.then(() =&gt; prepareItem(&quot;soda🥤&quot;));<br>    res3.then(serveOrder);<br>}<br>submitOrder();</pre><p>Assignment to separate response variables can be removed by <strong>chaining</strong>⛓ ‘<strong>then()</strong>’ calls as follows:</p><pre>function submitOrder() {<br>    prepareItem(&quot;hamburger🍔&quot;)<br>        .then(() =&gt; prepareItem(&quot;frenchFries🍟&quot;))<br>        .then(() =&gt; prepareItem(&quot;soda🥤&quot;))<br>        .then(serveOrder);<br>}<br>submitOrder();</pre><p>This looks more <strong>clean and readable</strong> than using nested callbacks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hv8XPM1Es3tAwOdnigwBUw.png" /><figcaption>Sequence diagram for Promise chaining</figcaption></figure><p>When there are more items in the order, the <strong>submitOrder()</strong> function can look as follows:</p><pre>function submitOrder(){<br>    prepareItem(&quot;coffee☕&quot;)<br>        .then(() =&gt; prepareItem(&quot;soda🥤&quot;))<br>        .then(() =&gt; prepareItem(&quot;frenchFries🍟&quot;))<br>        .then(() =&gt; prepareItem(&quot;hamburger🍔&quot;))<br>        .then(() =&gt; prepareItem(&quot;sandwich🥪&quot;))<br>        .then(serveOrder);<br>}<br>submitOrder();</pre><h3><strong>Async/Await</strong></h3><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function"><strong>async/await</strong></a> syntax was added to JavaScript in 2017. This is basically <strong>syntactic sugar</strong>🍚 for <strong>Promises</strong>🤝 which makes the asynchronous code look more <strong>sequential </strong>and<strong> </strong>makes the code easier to read.</p><p>The <strong>submitOrder()</strong> function can be written using this <strong>async/await</strong> syntax as follows:</p><pre>async function submitOrder(){<br>    await prepareItem(&quot;coffee☕&quot;);<br>    await prepareItem(&quot;soda🥤&quot;);<br>    await prepareItem(&quot;frenchFries🍟&quot;);<br>    await prepareItem(&quot;hamburger🍔&quot;);<br>    await prepareItem(&quot;sandwich🥪&quot;);<br>    completeOrder();<br>}<br>submitOrder();</pre><p>The <strong>await</strong> calls need to be wrapped inside an <strong>async</strong> function. So, the <strong>submitOrder()</strong> function is now marked as <strong>async</strong>. This can be called just like any other function.</p><p>The code now looks much cleaner and readable. It appears to be sequential when it is actually an abstraction for promises.</p><h3><strong>Conclusion</strong></h3><p>To wrap things up, we looked at how we can model the <strong>asynchronous</strong> behavior of JavaScript in terms of the working of a <strong>restaurant</strong>🤵👨‍🍳👨‍💼🍽️. We then looked at the different approaches JavaScript uses to model this asynchronous behavior using the restaurant code example.</p><p>We went through the difference between the <strong>Callback</strong> based approach and <strong>Promise </strong>based approach using the restaurant analogy. We also mentioned how to convert the promise-based code to <strong>async/await</strong> syntax.</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter here</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55c38d0517e0" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/asynchronous-javascript-the-restaurant-analogy-55c38d0517e0">Asynchronous JavaScript: The Restaurant Analogy</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>