<?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">
    <channel>
        <title><![CDATA[Anshuman's Dev Notes]]></title>
        <description><![CDATA[Anshuman's Dev Notes]]></description>
        <link>https://anshumanmahato.me/blogs</link>
        <generator>RSS for Node</generator>
        <lastBuildDate>Thu, 12 Mar 2026 03:39:36 GMT</lastBuildDate>
        <atom:link href="https://anshumanmahato.me/blogs/feed.xml" rel="self" type="application/rss+xml"/>
        <language><![CDATA[en]]></language>
        <ttl>60</ttl>
        <atom:link rel="first" href="https://anshumanmahato.me/blogs/feed.xml"/>
        <item>
            <title><![CDATA[Inside JavaScript Runtime Environment]]></title>
            <description><![CDATA[<p>Hey there! Welcome to another article in this series where we discuss the core fundamental concepts of this awesome yet messy language, JavaScript. In the previous article, we discussed how JavaScript executes code. We learned about the JavaScript Engine, its components, JavaScript code compilation, Execution Contexts, and the flow of JavaScript code execution. And we had some pizza too. If you missed it, check it out <a target="_blank" href="https://www.anshumanmahato.me/blogs/understanding-javascript-execution">here</a>.</p>
<p>Well, it was all about the execution of synchronous code. Then what about asynchronous code? - You may ask. Worry not, because that's what we will explore in this article. In the first article of this series, I briefly mentioned the Runtime Environment. Let's begin from there and dive deeper.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753870587473/aa7cd2b0-ecb0-4a07-8f58-9f612646f9dd.gif" alt="A man in an office setting energetically folding his arms with the caption &quot;LET'S DO THIS!&quot;" class="image--center mx-auto" /></p>
<h2 id="heading-the-javascript-runtime-environment">The JavaScript Runtime Environment</h2>
<blockquote>
<p><em>A JavaScript Runtime Environment is the environment that enables the execution of JavaScript Code.</em></p>
</blockquote>
<p>Wait what? Ain't that the Engine?</p>
<p>Hold up, let me clear this. The JavaScript Engine executes the code. The JavaScript Runtime Environment is what enables the Engine to do so. It defines the functionality that JavaScript can perform beyond just basic computation.</p>
<p>In the last article, I compared the JavaScript Engine to a cooking counter, remember? Now, can you have a cooking counter without a kitchen? No! It can be a home kitchen, a restaurant kitchen or maybe just a food truck. But there has to be a kitchen. The JavaScript Runtime Environment is that kitchen. The Engine is a part of the runtime environment. Yes, it is what executes the code. But, it is the Runtime Environment that facilitates, orchestrates and manages the process of execution.</p>
<p>Apart from the JavaScript Engine, the following are the other components of a JavaScript Runtime Environment -</p>
<ul>
<li><p>APIs and Libraries</p>
</li>
<li><p>Task Queues</p>
</li>
<li><p>Event Loop</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753870684512/f43aaba8-2156-4ad4-b170-3df5583f782f.jpeg" alt="Diagram showing the JavaScript Runtime Environment with four sections labeled: &quot;Engine,&quot; &quot;APIs &amp; Libraries,&quot; &quot;Task Queue,&quot; and &quot;Event Loop&quot;." class="image--center mx-auto" /></p>
<p>Let's go through all of these one at a time.</p>
<h2 id="heading-apis-and-libraries">APIs and Libraries</h2>
<p>These are pre-built functions and objects giving JavaScript access to system capabilities and external services, defining JavaScript's capabilities and functionalities for that Runtime Environment. Essentially, these are the tools and utilities that determine what JavaScript can do within that environment. So, will the capabilities of JavaScript differ from Runtime to Runtime, even if they use the same JavaScript Engine?</p>
<p>Well, Yeah! Think of the APIs like the utensils and facilities in a kitchen. Depending on the utensils, what you can cook will differ from one kitchen to another, even if they have the same cooking counter. The things you can do in a Bakery's kitchen will not be the same as those of an Asian Restaurant's kitchen. Come on! You can't be cooking Egg Fried Rice in a Bakery (unless you want to piss off Uncle Rogers 👀).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753870906060/e4a26446-8c9d-4df3-b943-36813345880a.gif" alt="Uncle Roger expressing frustration." class="image--center mx-auto" /></p>
<p>In a browser, for instance, you can manipulate web pages using DOM APIs, but you cannot access your computer's files directly. Switch to Node JS, and suddenly, you can interact with your operating system, but DOM manipulation is off-limits. Internally, both of these environments use the same Google V8 JavaScript Engine. The browser provides various Web APIs, including the DOM API, Timers API, History API, and Navigation API, among others. Node JS has C++ bindings for OS-level access and the Thread Pool. The JavaScript Engine does not inherently perform these by itself.</p>
<p>Whenever the JavaScript Engine encounters any tasks accessing these API's, such as a timeout or an AJAX call, it passes them to the Runtime Environment. Now, if these tasks are synchronous, the Engine will block the code execution and wait for the Runtime Environment to return. For asynchronous calls, the Engine does not wait. It passes them to the Runtime Environment and continues executing the code further. It's like baking a cake. You prepare the batter and place it in the oven to bake. And while the cake is in the oven, you prepare the frosting in the meantime.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753871859080/ab5b0e2c-c354-4713-bfba-cbb66c803b81.gif" alt="A setTimeout function is pushed to the call stack. It is then passed to the Web APIs area with its 5000ms timer running." class="image--center mx-auto" /></p>
<p>Okay, but then, what happens once the Runtime Environment finishes these tasks? Well, this is how it goes. When the Engine makes an asynchronous API call to the Runtime Environment, it also registers a <strong>Callback Function</strong> with the call. The direction for the Runtime Environment is that upon the <strong>"event"</strong> of completion of the task, call for the execution of the registered function.</p>
<pre><code class="lang-js"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span> alert(<span class="hljs-string">"Timeout Baby"</span>),<span class="hljs-number">5000</span>);
</code></pre>
<p>Take a look at the call for setting up a timeout after 5 seconds. The first argument is the callback function to execute whenever someone clicks the button. When the Engine encounters this statement, it does not wait for the timeout to happen. It offloads this task to the Runtime Environment and goes to the following statement. Now, whenever this timer runs out, the Runtime Environment queues the callback function for execution.</p>
<p>And how are these queued-up functions tracked and executed? Well, that's where the Task Queues and the Event Loop come into play.</p>
<h2 id="heading-task-queues-and-the-event-loop">Task Queues and the Event Loop</h2>
<p><strong>Task Queues</strong> are data structures that keep track of callback functions that are up for execution. But, before moving ahead with this, know that asynchronous APIs generally fall into two categories: <strong>Callback-based APIs</strong> and <strong>Promise-based APIs</strong>. The key difference is that Callback-based APIs require you to pass the callback function directly as an argument. In contrast, the Promise-based APIs return a Promise object that you can attach callbacks to using <code>.then()</code> or handle with async/await. Don't worry if you have no idea about Promises. We don't need to understand them in depth at present. For now, think of it like getting a payment from a client. You can either give them your payment details and the directions to make the payment (Callback), or they can write you a check (Promise) that you can cash out yourself.</p>
<p>But if we don't need to know them just yet, then why am I telling you all this? That's because where the attached callback functions get queued depends on the type of API that registered them. There are two separate queues for both of them.</p>
<ul>
<li><p><strong>Macrotask Queue</strong>, also known as Callback Queue, tracks functions queued by Callback-based APIs.</p>
</li>
<li><p><strong>Microtask Queue</strong> tracks functions queued by settled Promises.</p>
</li>
</ul>
<p>Here, the queued functions wait for the Call Stack to be empty. Once empty, these functions are moved to the Call Stack in FIFO (First In First Out) order for execution.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753871940660/4b11b977-690e-4df5-a551-17972391662d.gif" alt="After the 5000ms timer finishes, the callback is moved from the Web API section to the macrotask queue, waiting for execution." class="image--center mx-auto" /></p>
<p>The <strong>Event Loop</strong> handles this entire process. It is a mechanism that continuously monitors the call stack and the queues. Whenever the Call Stack is empty, it checks the Task Queues for queued functions and moves them to the Call Stack for execution, if there are any. This cycle repeats indefinitely as long as the application is running.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753871993319/4cd852c6-6f55-4fcd-803c-99df4b3cee9f.gif" alt="The event loop checks that the call stack is clear and pushes the macrotask (timeout callback) onto the call stack for execution." class="image--center mx-auto" /></p>
<p>The Event Loop has a priority for the Microtask Queue. So, it first checks the microtask queue. If there are any microtasks, they are pushed to the call stack for execution until the queue is empty. Only after the Microtask queue is empty does it check the Macrotask queue. Okay, so if the Microtask queue has priority over the Macrotask queue, what will happen if there are a lot of Microtasks? Wouldn't the Macrotask Queue be starved?</p>
<p>You know what, I'll leave that for you to ponder. Think about it. Also, feel free to let me know what you got.</p>
<h2 id="heading-non-blocking-concurrency-model"><strong>Non-blocking Concurrency Model</strong></h2>
<p>This entire flow we've been exploring, i.e., the Runtime Environment, Task Queues, Event Loop, and the orchestration of synchronous and asynchronous code, represents JavaScript's <strong>Non-blocking Concurrency Model</strong>.</p>
<p>Even though JavaScript is single-threaded, it achieves concurrency through this elegant system. The Engine never stops and waits for asynchronous operations to complete. Instead, it hands them off to the Runtime Environment and continues executing, allowing multiple tasks to be "in progress" simultaneously while keeping the main thread responsive and unblocked.</p>
<p>I know this has been a lot of theory stuff. So let me help you visualise this with a simple example. Take a look here.</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Script start"</span>); <span class="hljs-comment">// sync</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Timeout callback"</span>), <span class="hljs-number">0</span>);  <span class="hljs-comment">// async (macrotask)</span>
<span class="hljs-built_in">Promise</span>.resolve().then(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Promise microtask"</span>));  <span class="hljs-comment">// async (microtask)</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Script end"</span>); <span class="hljs-comment">// sync</span>
</code></pre>
<p>Let's trace through this code and see how the JavaScript Runtime Environment handles it.</p>
<p>When the script starts running, the JavaScript Engine begins executing the synchronous code line by line. The first line, <code>console.log("Script start")</code>, is synchronous, so it executes immediately and prints <em>"Script start"</em> to the consoleno queues involved here - just straight execution.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753872168945/ead8cb2f-469a-4f7a-9ba7-8ba84d697210.gif" alt="The JavaScript engine begins execution. &quot;Script start&quot; is logged synchronously to the console." class="image--center mx-auto" /></p>
<p>Next comes the interesting part: <code>setTimeout(() =&gt; { console.log("Timeout callback"); }, 0)</code>. Even though the delay is 0 milliseconds, this is still an asynchronous callback-based API call. The Engine doesn't execute the callback immediately. Instead, it hands this task over to the Runtime Environment and registers the callback function. The Runtime Environment will queue this callback in the Macrotask Queue once the timer expires, which happens instantly. But it still goes through the queue system because that's how asynchronous operations work in JavaScript.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753872198815/8cff7ce0-493b-42bc-9769-551c2c677b3d.gif" alt="The setTimeout callback is registered and delegated to the Web APIs. Control moves to the next statement." class="image--center mx-auto" /></p>
<p>The third line brings us another asynchronous operation: <code>Promise.resolve().then(() =&gt; { console.log("Promise microtask"); })</code>. It is a Promise-based API, and while the Promise resolves immediately, the <code>.then()</code> callback doesn't execute right away. The Runtime Environment queues this callback in the Microtask Queue, separate from the setTimeout callback we just saw.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753872308658/dce50c84-dd37-454c-a337-b986cb4e2758.gif" alt="The resolved Promises .then() callback is added to the microtask queue." class="image--center mx-auto" /></p>
<p>Finally, we have <code>console.log("Script end")</code>, which is another synchronous operation. It executes immediately and prints <em>"Script end"</em> to the console. At this point, the Engine has executed all the synchronous code, and the Call Stack is empty.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753872319172/e97add26-4205-46de-b347-0f976886a18b.gif" alt="&quot;Script end&quot; is logged synchronously." class="image--center mx-auto" /></p>
<p>Now here's where the Event Loop takes centre stage! With the Call Stack empty, the Event Loop checks the queues for any pending callbacks. Remember, it prioritises the Microtask Queue first? So it grabs the Promise callback from the Microtask Queue and pushes it to the Call Stack for execution, printing <em>"Promise microtask"</em>. Only after the Microtask Queue is empty does the Event Loop check the Macrotask Queue and execute the setTimeout callback, printing <em>"Timeout callback"</em>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753872328043/d11ccaf8-695b-4e13-a86f-f4ce4671fd2e.gif" alt="The call stack is empty. The microtask queue runs next. &quot;Promise microtask&quot; is logged. After all microtasks are completed, the macrotask (timeout callback) runs. &quot;Timeout callback&quot; is logged." class="image--center mx-auto" /></p>
<p>Here's our final output:</p>
<pre><code class="lang-bash">Script start
Script end
Promise microtask
Timeout callback
</code></pre>
<p>Pretty neat how the Event Loop orchestrates everything, right? It is JavaScript's Non-blocking Concurrency Model at work - the Engine stays responsive, processes synchronous code immediately, delegates asynchronous tasks to the Runtime Environment, and the Event Loop ensures everything gets executed in the proper order without ever blocking the main thread. And that's the beauty of JavaScript's approach to concurrency - it's simple, predictable, and incredibly effective at keeping applications responsive while handling complex asynchronous operations.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>And there you have it! We've journeyed through the fascinating world of JavaScript's Runtime Environment and discovered how it enables JavaScript's Non-blocking Concurrency Model. From understanding how the Engine works with APIs and libraries, to seeing how Task Queues and the Event Loop orchestrate asynchronous operations, we've uncovered the magic behind JavaScript's ability to stay responsive while handling complex tasks.</p>
<p>I hope this deep dive helped clarify some of the mysteries of JavaScript execution! If you found this article helpful, I'd love to hear your thoughts. Did anything surprise you? Do you have questions about specific scenarios? Your feedback means a lot to me. So, feel free to connect with me on:</p>
<ul>
<li><p>X: <a target="_blank" href="https://x.com/AnshumanMahato_">@AnshumanMahato_</a></p>
</li>
<li><p>LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/anshuman-mahato/">/in/anshuman-mahato/</a></p>
</li>
<li><p>GitHub: <a target="_blank" href="https://github.com/AnshumanMahato">/AnshumanMahato</a></p>
</li>
</ul>
<p>And if you enjoyed this article, don't forget to share it with fellow developers who might benefit from understanding JavaScript's inner workings.</p>
<p>Until next time, keep coding and stay curious! 🚀</p>
]]></description>
            <link>https://anshumanmahato.me/blogs/inside-javascript-runtime-environment</link>
            <guid isPermaLink="true">https://anshumanmahato.me/blogs/inside-javascript-runtime-environment</guid>
            <category><![CDATA[JavaScript]]></category>
            <category><![CDATA[fundamentals]]></category>
            <category><![CDATA[Web Development]]></category>
            <category><![CDATA[Programming Blogs]]></category>
            <dc:creator><![CDATA[Anshuman Mahato]]></dc:creator>
            <pubDate>Wed, 30 Jul 2025 14:18:04 GMT</pubDate>
            <cover_image>https://cdn.hashnode.com/res/hashnode/image/upload/v1753872600567/c1572a57-41fc-45f9-a393-0d5be05e1595.png</cover_image>
        </item>
        <item>
            <title><![CDATA[Understanding JavaScript Execution with some Pizza]]></title>
            <description><![CDATA[<p>Welcome back, fellow developers! I'm excited to have you here for the next part of our JavaScript deep-dive series. The previous article explored the fundamental concepts and core features that make JavaScript a powerful language. Don't worry if you missed it - you can catch up <a target="_blank" href="https://www.anshumanmahato.me/blogs/javascript-fundamentals-you-should-know">here</a>.</p>
<p>I was all set to explore JavaScript code execution. Now that I am here, all of a sudden, I am craving some homemade Pizza. You know what? How about we do both? After all, both coding and cooking are about following a recipe, executing steps in the right order, and creating something amazing from basic ingredients.</p>
<p>Today, we will unravel one of JavaScript's most intriguing aspectshow JS code is processed and executed. We'll peek behind the curtain to understand what happens when our JS code executes while baking a cheesy corn pizza.</p>
<p>So preheat your brain (and maybe your oven), and let's dive into this tasty technical adventure!</p>
<p><img src="https://media1.tenor.com/m/VALgpQf30oYAAAAd/gordon-ramsay-lets-go.gif" alt="Chef wearing a white uniform, smiling and hugging a child, with the caption &quot;Let's go!&quot;" class="image--center mx-auto" /></p>
<h2 id="heading-the-javascript-engine">The JavaScript Engine</h2>
<p>The execution of JavaScript code is handled by a program known as the JavaScript Engine or JS Engine. Just like Java requires JVM, JavaScript requires a <strong>JS Engine</strong>. All browsers and any other environment that executes JavaScript have a JS Engine, with Google's V8 Engine leading the pack as the powerhouse behind Chrome and Node.js. Firefox uses SpiderMonkey, Safari runs on JavaScriptCore, and several others.</p>
<p>The JS Engine has two key components - the Call Stack and the Heap. The <strong>Call Stack</strong> is where the code executes. On the other hand, the <strong>Heap</strong> is an unstructured memory space used for storing objects required by the code during execution. Think of JavaScript Execution as baking a pizza. The Cooking Area is your Engine, and the Cooking Counter is your Call Stack. The space over where you keep your ingredients is the Heap.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1740910742108/b15d2aca-9d6a-4973-b099-3d93bb4457b6.jpeg" alt="Diagram illustrating a JavaScript engine with two main sections: the Heap and the Call Stack. The Heap contains various colored blocks representing objects in memory, while the Call Stack includes stacked rectangles labeled as execution contexts." class="image--center mx-auto" /></p>
<p>Before you begin with the pizza, you have to prepare the ingredients. You cannot put them directly into the oven. You chop the vegetables, prepare the dough, grate the cheese, etc. Similarly, before the engine can execute the code, it has to be processed and converted to a machine-understandable form. It must speak the computer's language - machine code.</p>
<p>Earlier, we saw how JavaScript uses a clever hybrid approach called JIT Compilation, combining the best of compilation and interpretation. While I prepare the toppings for my pizza, let's peek under the hood and see how JIT Compilation inside the JS Engine.</p>
<h2 id="heading-just-in-time-compilation">Just-in-Time Compilation</h2>
<p>When code first arrives at the engine, something fascinating happens. The engine starts breaking down your code into meaningful pieces. It parses the code to segregate tokens holding some meaning to JavaScript, e.g., 'const', 'var', and 'for'. But it doesn't stop there. The engine then transforms these pieces into an <strong>Abstract Syntax Tree (AST)</strong> - a structured way for the engine to understand your code's intent. Let's take a simple example: for the line <code>const a = 10;</code>, here's what the AST looks like.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"type"</span>: <span class="hljs-string">"Program"</span>,
  <span class="hljs-attr">"start"</span>: <span class="hljs-number">0</span>,
  <span class="hljs-attr">"end"</span>: <span class="hljs-number">13</span>,
  <span class="hljs-attr">"body"</span>: [
    {
      <span class="hljs-attr">"type"</span>: <span class="hljs-string">"VariableDeclaration"</span>,
      <span class="hljs-attr">"start"</span>: <span class="hljs-number">0</span>,
      <span class="hljs-attr">"end"</span>: <span class="hljs-number">13</span>,
      <span class="hljs-attr">"declarations"</span>: [
        {
          <span class="hljs-attr">"type"</span>: <span class="hljs-string">"VariableDeclarator"</span>,
          <span class="hljs-attr">"start"</span>: <span class="hljs-number">6</span>,
          <span class="hljs-attr">"end"</span>: <span class="hljs-number">12</span>,
          <span class="hljs-attr">"id"</span>: {
            <span class="hljs-attr">"type"</span>: <span class="hljs-string">"Identifier"</span>,
            <span class="hljs-attr">"start"</span>: <span class="hljs-number">6</span>,
            <span class="hljs-attr">"end"</span>: <span class="hljs-number">7</span>,
            <span class="hljs-attr">"name"</span>: <span class="hljs-string">"a"</span>
          },
          <span class="hljs-attr">"init"</span>: {
            <span class="hljs-attr">"type"</span>: <span class="hljs-string">"Literal"</span>,
            <span class="hljs-attr">"start"</span>: <span class="hljs-number">10</span>,
            <span class="hljs-attr">"end"</span>: <span class="hljs-number">12</span>,
            <span class="hljs-attr">"value"</span>: <span class="hljs-number">10</span>,
            <span class="hljs-attr">"raw"</span>: <span class="hljs-string">"10"</span>
          }
        }
      ],
      <span class="hljs-attr">"kind"</span>: <span class="hljs-string">"const"</span>
    }
  ],
  <span class="hljs-attr">"sourceType"</span>: <span class="hljs-string">"module"</span>
}
</code></pre>
<p>Don't worry too much about the details of AST for now - but if you're curious to dive deeper, check out this <a target="_blank" href="https://dev.to/marvinjude/abstract-syntax-trees-and-practical-applications-in-javascript-4a3">article</a>.</p>
<p>The parsing phase does more than create the AST  it's your code's first quality check, handling transpilation, linting, and ensuring your syntax is spot-on. Once the engine parses the code to AST, it compiles this AST to machine code, which is then immediately put into the Call Stack for execution. Here's where it gets interesting. Initially, the engine generates a rough, unoptimised version of the machine code to get things up and running as fast as possible. Then, while your code is executing, it continuously works in the background to optimise this code for better performance.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1740910807030/412af998-ef66-4602-bb1b-90576e876c6f.jpeg" alt="Just in Time Compilation" class="image--center mx-auto" /></p>
<p>While different JavaScript engines might handle these steps in their own ways, this is basically how Just-in-Time Compilation works in JavaScript. It's a clever balance between speed and optimisation.</p>
<p>Now that my toppings are ready, its time to bake the pizza. Lets do that alongside learning how the engine executes the compiled code.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1740911202958/0d5ac796-887e-4109-b479-5eac46488271.jpeg" alt="A plate with a serving of sauted paneer cubes, sliced red onions, and a portion of corn kernels. The plate has a decorative floral design." class="image--center mx-auto" /></p>
<h2 id="heading-execution-context">Execution Context</h2>
<p>Once the code is parsed and compiled, it is ready for execution. As stated previously, the Call Stack is responsible for executing the code. It does so using something known as an Execution Context.</p>
<p>An <strong>Execution Context</strong> is an environment where a piece of code executes. Each context is like a self-contained environment that includes not just the code in execution but everything it needs to run  your variables, functions, objects, and more. Back to our cooking analogy, pots, pans, pizza trays, and all cooking vessels are the execution contexts.</p>
<p>We have two types of Execution Contexts: Function Execution Context and Global Execution Context. A <strong>Function Execution Context</strong> forms the environment for executing a function's code whenever we call it. Every function call creates a new separate execution context. The <strong>Global Execution Context</strong> is for the Top-Level code, i.e., the code which is not a part of any function. It is the first execution context to go into the call stack when execution begins. There is only one Global Execution Context, unlike Function Contexts, which can be many.</p>
<p>The code execution begins as the engine pushes the Global Execution context into the Call Stack. The code executes line by line until it hits a function call. Upon hitting a function call, the execution pauses for the current context, and its state is saved. The engine creates a new execution context for the called function and pushes it into the Call Stack on top of the current context. Control then moves to this new context, and execution starts from the first line of the function's body. This process is known as Context Switching. It happens every time the Call Stack encounters a function call.</p>
<p>Once the Execution Context successfully executes the last line of the function associated with the context, the Call Stack pops it off, and the control passes to the previous Execution Context. The execution resumes from the position where it stopped before context switching. The process continues until the Call Stack pops off the Global Execution Context.</p>
<p>Well, that was a lot of jibber jabber. Let's make some pizza and see this in action.</p>
<p><img src="https://media1.tenor.com/m/6omVw7_jl7AAAAAC/tmnt-michelangelo.gif" alt="a teenage mutant ninja turtle is holding three pizzas and saying it 's pizza time .." class="image--center mx-auto" /></p>
<h2 id="heading-code-execution-in-action">Code Execution in Action</h2>
<p>Here's our pizza recipe. Let's see how our JS engine will process it.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">prepareDough</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Step 1: Preparing Dough"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">" - 2 cups all-purpose flour"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">" - 1 tsp yeast"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">" - 1/2 tsp salt"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">" - 1 tsp sugar"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">" - 3/4 cup warm water"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">" - 1 tbsp olive oil"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Step 2: Mixing ingredients and kneading the dough."</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Step 3: Letting the dough rest for 1 hour."</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">prepareSauce</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Step 4: Preparing Tomato Sauce"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">" - 1/2 cup tomato puree"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">" - 1/2 tsp salt"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">" - 1/2 tsp oregano"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">" - 1/4 tsp black pepper"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">" - 1/2 tsp garlic powder"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Step 5: Cooking sauce for 10 minutes."</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">prepareToppings</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Step 6: Preparing Toppings"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">" - 1/2 cup grated mozzarella cheese"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">" - 1/2 cup sweet corn"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">" - 1/4 cup chopped bell peppers (optional)"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">assemblePizza</span>(<span class="hljs-params"></span>) </span>{
    prepareDough();
    prepareSauce();
    prepareToppings();
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Step 7: Rolling out the dough into a pizza base."</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Step 8: Spreading the sauce over the dough."</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Step 9: Adding cheese, corn, and other toppings."</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bakePizza</span>(<span class="hljs-params"></span>) </span>{
    assemblePizza();
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Step 10: Baking Pizza"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">" - Preheating oven to 220C (430F)."</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">" - Baking for 12-15 minutes until golden brown."</span>);
}

bakePizza();
</code></pre>
<p>Once the engine compiles your code, it kicks things off by placing the Global Execution Context (GEC) in the Call Stack. First up, the engine scans through your code and sets aside memory for all your pizza-making functions: <code>prepareDough()</code>, <code>prepareSauce()</code>, <code>prepareToppings()</code>, <code>assemblePizza()</code>, and <code>bakePizza()</code>. When it hits the <code>bakePizza()</code> call, the engine pauses the Global Context, creates a fresh Execution Context for <code>bakePizza()</code>, and adds it to the Call Stack.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1740912832305/cf993a5a-b817-4868-ae11-da8ffa0261a0.gif" alt="An animation demonstrating the JavaScript execution context, where the global execution context is created, followed by function calls like 'bakePizza()'. The call stack dynamically updates as functions are pushed and popped." class="image--center mx-auto" /></p>
<p>As <code>bakePizza()</code> springs into action, it needs <code>assemblePizza()</code> to do its job. The engine creates another Execution Context that jumps onto the Call Stack. Now, <code>assemblePizza()</code> starts with <code>prepareDough()</code> - yes, you guessed it, another Execution Context joins the stack! After logging the dough preparation steps and finishing its job, <code>prepareDough()</code> context checks out and leaves the stack, handing control back to <code>assemblePizza()</code>. The same sequence plays out for <code>prepareSauce()</code> and <code>prepareToppings()</code> - each gets its own Execution Context, does its thing with the toppings, and exits the stack when done.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1740912877520/23180106-1b1d-49a4-a728-2b81e361dc35.gif" alt="An animation illustrating the JavaScript engine with heap memory and call stack. Functions related to assembling a pizza, such as adding dough, sauce, and toppings, are pushed onto the call stack and then removed as execution completes." class="image--center mx-auto" /></p>
<p>With all preparations complete, <code>assemblePizza()</code> handles the final assembly - rolling dough, spreading sauce, and adding toppings. Once done, it exits the Call Stack, passing control back to <code>bakePizza()</code>. Now, <code>bakePizza()</code> can do its part - handling the baking instructions and logging the final messages. After it completes its tasks, it leaves the Call Stack as well.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1740912926803/90bf34d7-a00d-4542-90c0-f5596933d20c.gif" alt="An animation showing the JavaScript call stack in action, executing functions step by step. Functions are added to the stack and removed as they complete, visualizing how JavaScript processes synchronous code execution." class="image--center mx-auto" /></p>
<p>When the Call Stack finally empties, we know our pizza-making program has completed its journey - all functions have done their jobs and returned home. And with this, my pizza is ready.</p>
<p>Speaking of which, writing this article has made me incredibly hungry. I think it's time for me to savour this tasty homemade pizza.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1740912999387/49779ffa-cd96-46de-92da-c04e344cb631.jpeg" alt="A small pizza topped with cheese, corn, and onion slices on a decorative plate." class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1740913274147/c6e0daf3-a824-49d8-b4b1-ea8b072673d7.jpeg" alt="A farmer in overalls and a cap stands in a field, smiling. Text reads: &quot;It ain't much, but it's honest work.&quot;" class="image--center mx-auto" /></p>
<h2 id="heading-wrapping-up">Wrapping Up!</h2>
<p>So, we've reached the end of our delicious journey through JavaScript's execution process! We've learned how the engine processes our code, manages execution contexts, and handles the call stack. What seems like simple scripting is a highly optimised and synchronised process under the hood.</p>
<p>Thanks for reading! I hope this article was insightful for you. I'll leave you here to digest all this information. If you found this helpful, pass it along to your fellow developers (maybe include a pizza when you do)!</p>
<p>Want to connect? Follow me on:</p>
<ul>
<li><p>X: <a target="_blank" href="https://x.com/AnshumanMahato_">@AnshumanMahato_</a></p>
</li>
<li><p>LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/anshuman-mahato/">/in/anshuman-mahato/</a></p>
</li>
<li><p>GitHub: <a target="_blank" href="https://github.com/AnshumanMahato">/AnshumanMahato</a></p>
</li>
</ul>
<p>Happy Learning!! 😊🙏</p>
]]></description>
            <link>https://anshumanmahato.me/blogs/understanding-javascript-execution</link>
            <guid isPermaLink="true">https://anshumanmahato.me/blogs/understanding-javascript-execution</guid>
            <category><![CDATA[JavaScript]]></category>
            <category><![CDATA[fundamentals]]></category>
            <category><![CDATA[basics of javascript]]></category>
            <dc:creator><![CDATA[Anshuman Mahato]]></dc:creator>
            <pubDate>Sun, 02 Mar 2025 13:03:55 GMT</pubDate>
            <cover_image>https://cdn.hashnode.com/res/hashnode/image/upload/v1740918855243/a81779db-b0e6-4856-b3d6-80ecfc0cfad0.jpeg</cover_image>
        </item>
        <item>
            <title><![CDATA[JavaScript Fundamentals You Should Know]]></title>
            <description><![CDATA[<p>Today, JavaScript is everywhere. Whether scrolling through your favourite social media feed, ordering takeout, or streaming music, JavaScript is quietly powering that smooth experience behind the scenes. If you are a Web Developer, you definitely use it one way or the other. JavaScript is the core of modern web development.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739008226746/1f7bfe92-cc58-47e3-bf7a-8012e850b225.png" alt="A tweet from &quot;gbae the app developer&quot; asks if programmers like JavaScript. An image shows a teapot labeled &quot;JavaScript&quot; pouring into four cups labeled &quot;Frontend,&quot; &quot;Backend,&quot; &quot;Mobile Apps,&quot; and &quot;Desktop Apps.&quot; A machine learning cup is also being filled." class="image--center mx-auto" /></p>
<p>It's pretty mind-blowing when you think about it - this language has transformed from a simple website enhancement tool into the backbone of the entire web. But have you ever stopped to wonder about what is happening under the hood? What's going on when you click that button or submit that form? How does JavaScript communicate with your browser to make magic happen on your screen?</p>
<p>In this series, I will try to answer all these questions. If you have ever pondered these, follow along with me. Let's begin with the first article in this series.</p>
<h2 id="heading-what-is-javascript">What is JavaScript?</h2>
<p>Across the internet, you'll find various answers: scripting language, high-level language, the language of the web and whatnot. Let me give you a descriptive definition of JavaScript.</p>
<p>"<em>JavaScript is a High-level, Dynamically Typed, Multi-paradigm, Garbage Collected, JIT Compiled, Single Threaded programming language with First class functions and Non-Blocking Event Loop Concurrency model.</em>"</p>
<p><img src="http://media1.tenor.com/m/c8XuSAqVh_wAAAAC/ocean-park-roy.gif" alt class="image--center mx-auto" /></p>
<p>Well, I know that's a lot of technical jargon. But don't worry - we will break it into bite-sized pieces that anyone can understand.</p>
<p>Let's tackle the basics first - I promise it's not as scary as it sounds!</p>
<ul>
<li><p><strong>High-Level Language:</strong> These programming languages allow humans to write computer programs without specific knowledge of the hardware. That's how we work in JavaScript. We focus on program logic, not low-level hardware details like memory management.</p>
</li>
<li><p><strong>Dynamically Typed:</strong> JavaScript is pretty laid back regarding how you declare variables. Unlike its stricter cousins (C, C++, and Java), which demand to know the exact type of data you're working with upfront, JavaScript figures it out by itself. We do not need to specify data types when declaring and defining variables.</p>
</li>
<li><p><strong>Multi-Paradigm:</strong> JavaScript is versatile because it supports procedural, object-oriented, and functional programming paradigms. It doesn't force you into one way of coding. You can organize your code any way you want. JavaScript's got your back!</p>
</li>
<li><p><strong>Garbage Collected:</strong> Garbage collection is a feature that tracks objects and variables created and frees their memory when they are no longer required. It is like having a tidy roommate who automatically cleans up after you. It keeps track of what you're using and what you're not, clearing out unused memory so your program runs smoothly.</p>
</li>
<li><p><strong>First Class Functions:</strong> In JavaScript, functions are objects as well. They're not just actions. They're values you can play with. Do you want to hand a function to another function as a parameter? Go for it! Store it in a variable? Absolutely! Return it from another function? You bet!</p>
</li>
</ul>
<p>Now that we've covered the basics, let's dive into more interesting stuff!</p>
<h2 id="heading-just-in-time-compilation">Just In Time Compilation</h2>
<p>Have you ever wondered how your computer understands JavaScript? JavaScript is a high-level language. A computer cannot execute it directly; instead, we convert the code to a machine-understandable form. Across all programming languages, the conversion of source code to machine code happens in one of the following two ways -</p>
<ul>
<li><p><strong>Compilation:</strong> The entire source code is converted into machine code at once and is stored separately. Then, we use this compiled file for execution. It's like meal-prepping for the week - you do all the work upfront!</p>
</li>
<li><p><strong>Interpretation:</strong>  This is more like having a real-time translator at a conference. The code gets translated line by line as it runs, with the interpreter working on the fly. Every time you run the program, the translator needs to be there doing its thing.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739081866687/ff51f5c8-d5e7-4e23-9b91-6924a565a15d.jpeg" alt="Flowchart comparing compilation and interpretation. Compilation: Source code is completely translated to machine code, which is executed, potentially with a delay. Interpretation: Source code is translated and executed line by line, leading directly to the program running." class="image--center mx-auto" /></p>
<p>Now, JavaScript? It's clever - it takes the "why not both?" approach. You may have heard that JS is an interpreted language. But that's not the complete truth. What JS does is known as JIT Compilation or "Just In Time" Compilation.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739011912291/5c6dad77-8794-41bd-b62e-274b06050ad1.png" alt="A SpongeBob SquarePants meme outlining the JavaScript compilation process. The sequence includes Babel transpiling, TypeScript transpiling, Webpack bundling, source code parsing to syntax tree, syntax tree conversion to binary form, and Just-In-Time (JIT) compilation." class="image--center mx-auto" /></p>
<p>JIT Compilation in JavaScript combines the best of both compilation and interpretation. Like compilation, the entire code converts to machine code at once. But, we do not store it in a separate binary file. Instead, the machine code executes as soon as the compilation ends, like interpreted languages.</p>
<p>This approach allows JavaScript to start quickly like an interpreted language while achieving performance similar to compiled languages for frequently executed code. It's constantly adapting and optimizing based on how your code actually runs - pretty smart, right?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739081838146/5c66e5db-9600-4cd8-b0f1-2969219fda2d.jpeg" alt="Flowchart illustrating JIT compilation in JavaScript. It shows source code being completely translated into machine code with no separate file, followed by immediate execution, resulting in the program running." class="image--center mx-auto" /></p>
<p>Different JavaScript engines (like V8 for Chrome or SpiderMonkey for Firefox) implement JIT compilation in their ways, but they all follow this general principle to balance speed and flexibility.</p>
<p>I won't get into the exact details. Let's leave that for another article (\#contentPlanning 😁).</p>
<h2 id="heading-single-threaded-programming-language">Single Threaded Programming Language</h2>
<p>JavaScript is a single-threaded programming language. As a result, it can only do one thing at a time. Think of JavaScript as a one-track mind - it's like a chef with a single cutting board who can only chop one ingredient at a time. Here's what this means in practice:</p>
<ol>
<li><p><strong>Execution Order</strong>: JavaScript code is executed line by line, from top to bottom, one step at a time. No skipping ahead or multitasking!</p>
</li>
<li><p><strong>Synchronous Execution</strong>: By default, JavaScript runs synchronously, meaning each line of code waits for the previous one to complete before executing.</p>
</li>
<li><p><strong>Blocking Operations</strong>: If a particular operation takes a long time to complete, it will block the execution of subsequent code until it finishes.</p>
</li>
</ol>
<p><img src="https://media.tenor.com/BB3sZELhyQgAAAAi/ermm-hmmm.gif" alt class="image--center mx-auto" /></p>
<p>Now, you might be scratching your head and thinking, "Wait a minute... if JavaScript can only do one thing at a time, wouldn't our apps freeze up whenever something takes too long?" Great question! Well, this is where the Event Loop comes into play.</p>
<h2 id="heading-non-blocking-event-loop-concurrency-model">Non Blocking Event Loop Concurrency Model</h2>
<p>A non-blocking event loop is a programming model that allows a single-threaded application to handle multiple concurrent operations efficiently without getting stuck or blocking the main execution thread. In simple terms, this is what happens. When JavaScript encounters a time-consuming task (like fetching data from a server or reading a file), instead of standing around waiting, it hands it off to the background workers in the Runtime Environment and keeps moving forward with other tasks.</p>
<p>Once that background task is complete, the Event Loop acts like a notification system, tapping JavaScript on the shoulder to say, "Hey, that thing you asked for? It's ready!" It brings the callbacks or the continuation of that task to the main thread.</p>
<p>It is just scratching the surface of how the Event Loop keeps everything running smoothly. We'll dive deeper into all its inner workings when we explore the JavaScript Runtime environment!</p>
<h2 id="heading-thats-all-for-now">Thats all for now !</h2>
<p>Well, that's all in this brief overview of JavaScript.  I hope it was helpful and informative for you. If your mind is buzzing with questions right now - perfect! That's what I was aiming for.</p>
<p>Stay tuned for the upcoming articles in this series, where we'll roll up our sleeves and dig deep into JavaScript's inner workings. No stone will be left unturned as we explore every nook and cranny of this fascinating language.</p>
<p>I'm super eager to hear your thoughts and experiences. If you want to connect with me, here are my socials:</p>
<p><a target="_blank" href="https://twitter.com/AnshumanMahato_">Twitter</a>    <a target="_blank" href="https://www.linkedin.com/in/anshuman-mahato/">LinkedIn</a>    <a target="_blank" href="https://github.com/AnshumanMahato">GitHub</a></p>
<p>Thanks for joining me on this JavaScript adventure! Remember - the best developers are the ones who never stop asking, "but how does it work?" Keep that curiosity burning! </p>
]]></description>
            <link>https://anshumanmahato.me/blogs/javascript-fundamentals-you-should-know</link>
            <guid isPermaLink="true">https://anshumanmahato.me/blogs/javascript-fundamentals-you-should-know</guid>
            <category><![CDATA[JavaScript]]></category>
            <category><![CDATA[fundamentals]]></category>
            <category><![CDATA[programming languages]]></category>
            <category><![CDATA[beginner]]></category>
            <dc:creator><![CDATA[Anshuman Mahato]]></dc:creator>
            <pubDate>Sun, 09 Feb 2025 10:45:31 GMT</pubDate>
            <cover_image>https://cdn.hashnode.com/res/hashnode/image/upload/v1739097760373/dcd95b63-1c50-4271-9cbb-702d1b8223d9.png</cover_image>
        </item>
        <item>
            <title><![CDATA[Mastering React Context: Simplifying State Management and Prop Drilling]]></title>
            <description><![CDATA[<p>Many times, in react, state information is used by multiple components. Information in React is usually shared using props. We use it for this purpose as well.</p>
<p>To resolve such situations, we define that data/function at a common parent component and then move it down using props. We call it <strong>lifting the state</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720089802793/34a6bb2e-44d2-40b1-aa32-7a97ba0d9b60.jpeg" alt="Independent states vs lift up" /></p>
<p>The <strong>Context API</strong> is an alternative to this. A context defines a scope with some information. All the components placed in this scope can use that information directly. In my opinion, it is similar to namespaces in C++.</p>
<h2 id="heading-the-problem-with-props">The Problem with Props</h2>
<p>Although passing props is a perfectly valid solution, it often creates an issue. There might be situations where the common parent is far from the actual component. So, we will need to move the data very deep down the UI tree and make it unnecessarily verbose. This issue is called <strong>"Prop Drilling"</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720089804314/ea0740f1-3fa7-4320-a3e7-9aece100593a.jpeg" alt="Prop Drilling" /></p>
<p>Let's take an example to understand this. Let's say we have a CRUD app related to Books. Following is the structure of this application.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720089805805/2ddb9a00-f1cb-48a7-aa51-4f6143a06dfe.jpeg" alt="Books app using prop drilling" /></p>
<p><code>&lt;BookCreate /&gt;</code> - Creates entry for the book. <code>&lt;BookList /&gt;</code> - Shows all the Books <code>&lt;BookShow /&gt;</code> - Display component for each book. <code>&lt;BookEdit /&gt;</code> - Component to editing book information.</p>
<p>The <code>books</code> array is a state variable that contains all the books, and <code>createBook</code>, <code>editBook</code>, and <code>deleteBook</code> are functions that manipulate the state.</p>
<p>As we can see, all the components use the <code>books</code> state. So, we declare in the App component. So are the functions that manipulate it.</p>
<p>Now, these functions need to be moved way down the component tree. We will require a lot of props, resulting in prop drilling.</p>
<p>We can avoid this issue using Contexts. Context lets a parent component provide data to the entire tree below it.</p>
<h2 id="heading-implementing-context">Implementing Context</h2>
<p>To implement a Context, you need to do the following three steps:</p>
<ol>
<li><p>Creating a context</p>
</li>
<li><p>Provide the context scope</p>
</li>
<li><p>Use the Context</p>
</li>
</ol>
<h3 id="heading-creating-a-context-object">Creating a Context object</h3>
<p>We use the <code>createContext()</code> method for this.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {createContext} <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">const</span> Context = createContext(defaultvalue);
</code></pre>
<p>This method returns a <code>context</code> object.</p>
<h3 id="heading-providing-the-context">Providing the Context</h3>
<p>Now, we create a scope using this <code>context</code> object. Here, we define the values to pass to the child components. The <code>context</code> object has a provider component for this purpose.</p>
<pre><code class="lang-javascript">&lt;Context.Provider value={valueToShare}&gt;
      {children}
&lt;/Context.Provider&gt;
</code></pre>
<p>This component has a <code>value</code> prop through which we associate values with the scope. The value of this prop becomes available to all the children components of the <code>Provider</code> component.</p>
<h3 id="heading-using-the-context-object">Using the <code>context</code> object</h3>
<p>The children components extract these values using the <code>useContext()</code> hook.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {useContext} <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">const</span> value = useContext(Context);
</code></pre>
<p>This hook takes the <code>context</code> object as an argument and returns the values that are associated with it.</p>
<p>Here's an example with a simple implementation using contexts.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//Context.jsx</span>

<span class="hljs-keyword">import</span> { createContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> Context = createContext(<span class="hljs-number">1</span>);

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Context;
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">//Container.jsx</span>

<span class="hljs-keyword">import</span> React, { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> Context <span class="hljs-keyword">from</span> <span class="hljs-string">"./Context"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Container</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> value = useContext(Context);
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>{value}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Container;
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">//App.jsx</span>

<span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> Context <span class="hljs-keyword">from</span> <span class="hljs-string">"./Context"</span>;
<span class="hljs-keyword">import</span> Container <span class="hljs-keyword">from</span> <span class="hljs-string">"./Container"</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Context.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{5}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Container</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Context.Provider</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/s/context-example-fu8ndo?fontsize=14&amp;hidenavigation=1&amp;module=%2Fsrc%2Fcomponents%2FApp.jsx,%2Fsrc%2Fcomponents%2FContainer.jsx,%2Fsrc%2Fcomponents%2FContext.jsx&amp;theme=dark&amp;moduleview=1&amp;view=split"><img src="https://codesandbox.io/static/img/play-codesandbox.svg" alt="Edit context-example" /></a></p>
<p>This way, information is shared between components without using any prop for passing data.</p>
<h2 id="heading-some-extra-bits-on-contexts">Some Extra bits on contexts</h2>
<ul>
<li><p>We can create multiple scopes using the same context object. We can provide each of them with different context values that the components within them can access. Replace the App code with the following code in the above example to see it live.</p>
<pre><code class="lang-javascript">  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Context.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{3}</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Container</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Context.Provider</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Context.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{7}</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Container</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Context.Provider</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
</code></pre>
</li>
<li><p>We can also define a scope within another scope of the same context object, and both will provide different values to their child components. Here, a child can access all the data values belonging to the nearest parent Provider. Replace the App code with the following code in the above example to see it live.</p>
<pre><code class="lang-javascript">  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Context.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{3}</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Container</span> /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Context.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{7}</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Container</span> /&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">Context.Provider</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Context.Provider</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
</code></pre>
</li>
<li><p>If a non-child component tries to use it, it gets the default value passed during the <code>createContext(defaultValue)</code> call. In such a situation, React searches for a parent provider for it. But as it does not find one, it returns the default value as a fallback. Replace the App code with the following code in the above example to see it live.</p>
<pre><code class="lang-javascript">  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Context.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{3}</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Container</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Context.Provider</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Container</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
</code></pre>
</li>
</ul>
<h2 id="heading-practical-use-case">Practical Use Case</h2>
<p>The most common use of contexts is <strong>State Management</strong>. Prop drilling often happens due to the sharing of state information between components. What would be better is to create a context for the state and put the component tree associated with that state within that.</p>
<p>Let's see our book example again. We declared the <code>books</code> state and associated methods in the <code>App</code> component. We then moved them to the actual location via props.</p>
<p>Alternatively, we can define the <code>books</code> state and the methods in a context and provide it to the App component. This way, the App and all its children components have access to the <code>books</code> state directly.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720089809176/a3da3876-bd85-407e-9198-7c1657bc9505.jpeg" alt="Books app using context" /></p>
<p>Here's the code for it</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://codesandbox.io/embed/bs3rzk?view=editor+%2B+preview&amp;module=%2Fsrc%2Findex.js">https://codesandbox.io/embed/bs3rzk?view=editor+%2B+preview&amp;module=%2Fsrc%2Findex.js</a></div>
<p> </p>
<h2 id="heading-some-consideration">Some Consideration</h2>
<p>Contexts are great tools for passing data deeply in a UI tree without tending to prop drilling. They are simple to implement, making it very tempting to use them. Thus, we may end up overusing them. To avoid this, we must understand the association between the information and the components using it.</p>
<ul>
<li><p>If the information is associated with components which are related and mutually dependent on one another, it might be better to use the prop system as it would make the data flow explicit between them. For example, let's say we have a Form component with multiple form controls. Different form controls may depend upon the states of one another and thus require the sharing of information. Here, using props would be better as it would depict how data flows within the Form component.</p>
</li>
<li><p>On the flip side, if the information is associated with mutually independent components, it is better to use contexts. An example of this could be login information. We can use this in the navbar to show the username. We can use this on the profile page to display user details. We can use it application-wide, irrespective of the relationship between the components.</p>
</li>
</ul>
<h2 id="heading-thats-all-folks">That's all folks</h2>
<p>This article is my understanding of the context API. Contexts are great for sharing information when it needs to be moved deeply in a component tree. It is simple to implement and helps in clubbing data in one place.</p>
<p>And hey, if you want to connect beyond these pages, catch me on Twitter! My handle is <a target="_blank" href="https://twitter.com/AnshumanMahato_">@AnshumanMahato_</a>.</p>
<p>With this, I would like to conclude this post. Until next time, stay curious and keep exploring! 🌟Thank You for reading this far. 😊</p>
]]></description>
            <link>https://anshumanmahato.me/blogs/mastering-react-context-simplifying-state-management-and-prop-drilling</link>
            <guid isPermaLink="true">https://anshumanmahato.me/blogs/mastering-react-context-simplifying-state-management-and-prop-drilling</guid>
            <category><![CDATA[React]]></category>
            <category><![CDATA[ReactHooks]]></category>
            <category><![CDATA[JavaScript]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Anshuman Mahato]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 11:08:28 GMT</pubDate>
            <cover_image>https://cdn.hashnode.com/res/hashnode/image/upload/v1720090837922/926bd14d-9eaf-4aa1-a1fc-28244f68ae9e.jpeg</cover_image>
        </item>
        <item>
            <title><![CDATA[For intricate state handling, try out the useReducer() Hook]]></title>
            <description><![CDATA[<p>So, lately, I have been working on a form component. It was a registration form that had quite a few fields in it. The state management for this was not complex, but it was repetitive. Creating a state for each input field and updating it whenever the user interacts with them, I was writing the same code with minor differences.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> [fname,setFname] = useState(<span class="hljs-string">""</span>);
<span class="hljs-keyword">let</span> [lname,setLname] = useState(<span class="hljs-string">""</span>);
<span class="hljs-keyword">let</span> [email,setEmail] = useState(<span class="hljs-string">""</span>);
...
</code></pre>
<p>Also, I felt that all these pieces must be related to one another rather than being separate entities. So, I switched to using a single state with an object storing all input fields.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> [formData, setFormData] = useState({
   <span class="hljs-attr">fname</span>: <span class="hljs-string">""</span>,
   <span class="hljs-attr">lname</span>: <span class="hljs-string">""</span>,
   <span class="hljs-attr">email</span>: <span class="hljs-string">""</span>,
   ... 
});
</code></pre>
<p>Even though the state was centralized, the event handlers still managed the state update logic.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> changeEmail = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
     <span class="hljs-keyword">const</span> regex = <span class="hljs-regexp">/^[a-zA-Z0-9.!#$%&amp;'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/</span>;

     <span class="hljs-keyword">if</span>(e.target.value.match(regex))
         setFormData({...state, <span class="hljs-attr">email</span>: e.target.value});
};
</code></pre>
<p>I was looking for some way to centralize this as well. That's when I came across the <code>useReducer()</code> hook, a utility for complex state management.</p>
<p>Want to know about this? Just follow along with me.</p>
<h2 id="heading-what-is-this-usereducer-hook-and-how-does-it-work">What is this useReducer() hook, and how does it work?</h2>
<p>The <code>useReducer()</code> hook is an alternative to the <code>useState()</code> hook that helps to manage complex states in a React application. In fact, the useState() hook uses the useReducer() hook behind the scenes itself.</p>
<p>The useReducer() hook takes a <code>reducer</code> function and the <code>initial state</code> as its parameter and returns an array. The first element of this array is the <code>state</code> object, and the second element is the <code>dispatch</code> function. At first, it might look very similar to useState(). But the working is very different here.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [state,dispatch] = useReducer(reducer,initialState);
</code></pre>
<p>The <code>state</code> and the <code>initialState</code> are obvious. But, what are <code>dispatch</code> and <code>reducer</code>? Let's try to understand how all this works.</p>
<h2 id="heading-reducer-actions-and-dispatch">Reducer, Actions and Dispatch</h2>
<p>The <code>dispatch</code> is analogous to the update function returned by the useState() hook. Both are used to update the state. The difference lies in how they work. Unlike the update function, where we pass the next state directly, we pass an <code>Action</code> here.</p>
<p>Now, you may ask, "What is this Action?". Well, An <code>Action</code> is an object that specifies how we want to update our state. You may structure your Action object as you wish. But conventionally, we have two fields in this object - <code>type</code> and <code>payload</code>. The type specifies the kind of update that we want to perform. The payload takes any external values that might be needed for the update.</p>
<pre><code class="lang-javascript">dispatch({<span class="hljs-attr">type</span>:<span class="hljs-string">"ACTION TYPE"</span>, <span class="hljs-attr">payload</span>:<span class="hljs-string">"values to pass"</span>});
</code></pre>
<p>What does the dispatch do with this Action object? It passes it to its associated reducer. The <code>reducer</code> is a function that maintains the logic for state updates for every action type. It takes the current state and an Action object as arguments and returns the updated state per the requested action. After this, the component is rendered according to the update state.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720089835518/84c05168-1c08-40b8-b08f-b5b843214ea0.jpeg" alt="State update flow in useReducer() hook" /></p>
<h2 id="heading-lets-try-this-out">Let's try this out</h2>
<p>Let us build a simple <code>Counter App</code> to see this working (cliche, I know). The application will have four functions -</p>
<ol>
<li><p>We can increment the count by 1.</p>
</li>
<li><p>We can decrease the count by 1.</p>
</li>
<li><p>We can add some value to the count.</p>
</li>
<li><p>We can subtract some value from the count.</p>
</li>
</ol>
<p>Let's begin with our initial state. It will only contain a field for the <code>count</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> initState = {<span class="hljs-attr">count</span>: <span class="hljs-number">0</span>};
</code></pre>
<p>Now, we implement our reducer function.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reducer</span>(<span class="hljs-params">state,action</span>) </span>{
   <span class="hljs-keyword">const</span> {type,payload} = action;
   <span class="hljs-keyword">const</span> {count} = state;
   <span class="hljs-keyword">switch</span>(type) {
      <span class="hljs-keyword">case</span> <span class="hljs-string">"INCREMENT"</span>: <span class="hljs-keyword">return</span> {...state, <span class="hljs-attr">count</span>: count + <span class="hljs-number">1</span>};
      <span class="hljs-keyword">case</span> <span class="hljs-string">"DECREMENT"</span>: <span class="hljs-keyword">return</span> {...state, <span class="hljs-attr">count</span>: count - <span class="hljs-number">1</span>};
      <span class="hljs-keyword">case</span> <span class="hljs-string">"ADD"</span>: <span class="hljs-keyword">return</span> {...state, <span class="hljs-attr">count</span>: count + payload.value};
      <span class="hljs-keyword">case</span> <span class="hljs-string">"SUBTRACT"</span>: <span class="hljs-keyword">return</span> {...state, <span class="hljs-attr">count</span>: count - payload.value};
      <span class="hljs-keyword">default</span>: <span class="hljs-keyword">return</span> state;
   }
}
</code></pre>
<p>It's time to implement our Counter component.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Counter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [state, dispatch] = useReducer(reducer, initState);
  <span class="hljs-keyword">const</span> [value, setValue] = useState(<span class="hljs-number">0</span>);
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{state.count}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> dispatch({ type: "INCREMENT" })}&gt;Increment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> dispatch({ type: "DECREMENT" })}&gt;Decrement<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span>
          <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span>
          <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setValue(parseInt(e.target.value))}
        /&gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> dispatch({ type: "ADD", payload: { value } })}&gt;
          Add
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
          <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> dispatch({ type: "SUBTRACT", payload: { value } })}
        &gt;
          Subtract
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Counter;
</code></pre>
<p>And with this, our component is complete. Copy this code and play around with it to understand things better.</p>
<h2 id="heading-things-to-consider">Things to consider</h2>
<p>Here are some points to remember when working with the <code>useReducer()</code> hook.</p>
<ol>
<li><p>Do not use them anywhere and everywhere. Use it only where the structure of the state is somewhat complex. Otherwise, you'll be writing unnecessarily lengthy codes. For simple states, stick to the useState() hook.</p>
</li>
<li><p>Storing action types as constants is better than using literals. It helps in avoiding bugs due to typos.</p>
</li>
<li><p>Always return a new object from the reducer when updating the state. React makes a <code>shallow comparison</code> when comparing new and old states. Updating a particular field will not trigger re-renders.</p>
</li>
</ol>
<h2 id="heading-thats-all-folks">That's all Folks</h2>
<p>That's a wrap for now, folks! I hope this article was insightful to you. I look forward to your insights and feedback.</p>
<p>If you want to connect beyond these pages, these are the places where you can find me!</p>
<p><a target="_blank" href="https://twitter.com/AnshumanMahato_">Twitter</a></p>
<p><a target="_blank" href="https://www.linkedin.com/in/anshuman-mahato/">LinkedIn</a></p>
<p><a target="_blank" href="https://github.com/AnshumanMahato">GitHub</a></p>
<p>Until next time, stay curious and keep exploring!🌟 Thank You for reading this far. 😊</p>
]]></description>
            <link>https://anshumanmahato.me/blogs/for-intricate-state-handling-try-out-the-usereducer-hook</link>
            <guid isPermaLink="true">https://anshumanmahato.me/blogs/for-intricate-state-handling-try-out-the-usereducer-hook</guid>
            <category><![CDATA[React]]></category>
            <category><![CDATA[ReactHooks]]></category>
            <category><![CDATA[JavaScript]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Anshuman Mahato]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 10:53:24 GMT</pubDate>
            <cover_image>https://cdn.hashnode.com/res/hashnode/image/upload/v1720089836914/9511222a-d4bc-4efd-a44a-609d598c2f45.png</cover_image>
        </item>
    </channel>
</rss>