<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Azhar Dev</title>
    <description>The latest articles on DEV Community by Azhar Dev (@idrazhar).</description>
    <link>https://dev.to/idrazhar</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F683437%2Fe323a8d4-42ac-463c-89c6-3fc599cb82c8.png</url>
      <title>DEV Community: Azhar Dev</title>
      <link>https://dev.to/idrazhar</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/idrazhar"/>
    <language>en</language>
    <item>
      <title>0 to 1 — Asynchronous JavaScript</title>
      <dc:creator>Azhar Dev</dc:creator>
      <pubDate>Sun, 14 Aug 2022 09:09:16 +0000</pubDate>
      <link>https://dev.to/idrazhar/0-to-1-asynchronous-javascript-4iil</link>
      <guid>https://dev.to/idrazhar/0-to-1-asynchronous-javascript-4iil</guid>
      <description>&lt;p&gt;If you have put some effort into learning actually is JavaScript. You must be really confused, as I was when I was understanding this beautiful language. Let me tell you why I was confused at that time, and probably your reasons should be similar too. If you research JavaScript, you usually get two types of statements.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;JavaScript is a single-threaded, synchronous, blocking programming or scripting language.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let's break this statement down;&lt;br&gt;
&lt;strong&gt;Single-threaded&lt;/strong&gt;: JavaScript is single-threaded in nature because the browser executes the complete script in a single execution thread. JavaScript engine executes our program &lt;strong&gt;sequentially&lt;/strong&gt; one after another, a statement by statement.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Synchronous&lt;/strong&gt;: JavaScript is synchronous in nature because everything is executed in sync. The next statement(program)has to sit and wait until the currently executing one is completed. Once the program is completed, the next one becomes active.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Blocking&lt;/strong&gt;: As JavaScript executes our programs sequentially, statement by statement. JavaScript engine blocks the execution of the next program until our current program is completed. Does not matter how long our program is taking to complete, JavaScript would never bypass our program, thus blocking the rest of the code.&lt;/p&gt;

&lt;h3&gt;
  
  
  Dual Faced JavaScript
&lt;/h3&gt;

&lt;p&gt;Well at some points of your research, you might have also encountered somewhere something like;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;JavaScript is asyncronous in nature.&lt;br&gt;
JavaScript is non-blocking programming language&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now see what this means actually;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Asynchronous&lt;/strong&gt;: JavaScript is asynchronous means, it does not wait for a program to complete if it is taking too long, it simply bypasses it and moves to the very next program.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Non-blocking&lt;/strong&gt;: Similarly, JavaScript doesn’t block the execution of our program if our current program is taking longer. JavaScript parks our guilty program and moves to the next program, thus non-blocking in nature.&lt;/p&gt;

&lt;h3&gt;
  
  
  Which JavaScript face is the correct face?
&lt;/h3&gt;

&lt;p&gt;Well, let's clear our confusion. JavaScript is &lt;strong&gt;synchronous and asynchronous&lt;/strong&gt; at the same time. Well, no doubt, JavaScript is synchronous by default. But that doesn’t mean you cannot run it asynchronously. We can make JavaScript run our code asynchronously by using various means. Which we will be discussing in a short while.&lt;/p&gt;

&lt;h3&gt;
  
  
  Synchronous JavaScript
&lt;/h3&gt;

&lt;p&gt;I am pretty sure you are already well aware of the synchronous face of JavaScript, well we will be talking about Asynchronous JavaScript in this guide. Consider this very simple program which is handled synchronously(default behavior);&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--uOWMSVqc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ujwmkyil9l9djf6pi09.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--uOWMSVqc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ujwmkyil9l9djf6pi09.png" alt="Synchronous JavaScript Program" width="880" height="453"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This program logs everything in sequence, &lt;/p&gt;

&lt;p&gt;&lt;code&gt;Program Start&lt;/code&gt; → &lt;code&gt;Function Start&lt;/code&gt; → &lt;code&gt;Function End&lt;/code&gt; → &lt;code&gt;Program End&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;You are already well aware of this behavior so we will not be wasting any time on this.&lt;/p&gt;

&lt;h3&gt;
  
  
  Guide Outcomes
&lt;/h3&gt;

&lt;p&gt;I follow along me, at the end of this article you will be able to answer all of these questions.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;em&gt;What is Asynchronous JavaScript? And why do we need asynchronous JavaScript?&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;How do we implement Asynchronous JavaScript in our code?&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;What are Web APIs? And what Web APIs can be helpful in writing Asynchronous JavaScript code?&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;What are callback functions? And we can write asynchronous code with them?&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;What are Promises in JavaScript? And what is their role in modern asynchronous JavaScript?&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;What are the microTask queue and the Callback queue in JavaScript?&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is Asynchronous JavaScript? And why do we need asynchronous JavaScript?
&lt;/h2&gt;

&lt;p&gt;As we already know JavaScript is synchronous in nature by default. It executes every program sequentially and blocks the next program until the completion of the currently executing program.&lt;/p&gt;

&lt;p&gt;But, What if we need do not need to run our code immediately? We need to park our function to be executed in the future under specific conditions.&lt;/p&gt;

&lt;p&gt;What if our program takes a bit longer to complete? Our complete program would freeze until its completion.&lt;/p&gt;

&lt;p&gt;What if our program needs some external data, and makes an API call to the server? Of course, depending on the speed of the server, it would take some time to receive a response from the server.&lt;/p&gt;

&lt;p&gt;I can give you many scenarios, which make asynchronous JavaScript necessary.&lt;/p&gt;

&lt;h2&gt;
  
  
  How do we implement Asynchronous JavaScript in our code?
&lt;/h2&gt;

&lt;p&gt;We can write asynchronous JavaScript logic in our program in a number of ways. Modern JavaScript and Web browsers provide us with these major means to write asynchronous JavaScript code;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;em&gt;Web APIs&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;Callback functions&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;Promises (replacement of callback functions)&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Web APIs
&lt;/h2&gt;

&lt;p&gt;To understand Web APIs properly, we need to know little behind-the-scenes of javascript. For those who do not know, our browser is the place where JavaScript code is executed. Our browser provides our code with a special environment called the &lt;strong&gt;Runtime Environment&lt;/strong&gt;. Runtime environment actually comprise four major components;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;em&gt;JavaScript engine&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;Web APIs&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;The Eventloop&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;The callback(task) queue&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you want to learn more about JavaScript Runtime Environment and working of JavaScript behind the scenes, Check out my extensive guide on &lt;a href="https://medium.com/@idrazhar/0-to-1-series-how-javascript-works-under-the-hood-ffca74f1cc65"&gt;Working of JavaScript under the hood&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Here our main concern is Web APIs. JavaScript runtime environment exposes our code with some extra features provided by the browser client. We can use these features in our application to gain extra power.&lt;/p&gt;

&lt;p&gt;Common Asynchronous Web APIs&lt;br&gt;
If have been using JavaScript for a while now, you must be already aware of the popular Web APIs like the &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model"&gt;DOM API&lt;/a&gt;, &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API"&gt;fetch API&lt;/a&gt;, and the &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API"&gt;Canvas API&lt;/a&gt;. You can check the complete list of popular Web APIs &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Here, we are only interested in asynchronous Web APIs, like the fetch API, &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/setTimeout"&gt;setTimeout()&lt;/a&gt;, &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/setInterval"&gt;setInterval()&lt;/a&gt;, etc.&lt;/p&gt;

&lt;p&gt;Consider this example where we are using fetch API to load resources from the server asynchronously. Let's assume our request is gonna take 1 second (&lt;strong&gt;1000ms&lt;/strong&gt;) to return a response.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--g1sOoQ8V--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7to6b9g6r4uk4qb049tr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--g1sOoQ8V--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7to6b9g6r4uk4qb049tr.png" alt="Fetch API asynchrnous call" width="880" height="534"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;First I want you to guess the output in the console. If you guessed;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Program Start&lt;/code&gt; → &lt;code&gt;Function Start&lt;/code&gt; → &lt;code&gt;Program end&lt;/code&gt; → &lt;code&gt;1000ms Delay&lt;/code&gt; → &lt;code&gt;Fetch call response&lt;/code&gt; → &lt;code&gt;Function End&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;You are right. What will be the output of this code, if the fetch API was synchronous? Here.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Program Start&lt;/code&gt; → &lt;code&gt;Function Start&lt;/code&gt; → &lt;code&gt;1000ms Delay&lt;/code&gt; → &lt;code&gt;Fetch call response&lt;/code&gt; → &lt;code&gt;Function End&lt;/code&gt; → &lt;code&gt;Program end&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;We can clearly see that our fetch call to the server was handled &lt;strong&gt;asynchronously&lt;/strong&gt; because we are using a special fetch Web API. Our program starts, call to the server is initiated. But instead of waiting for the server to return some response, the JavaScript engine moves to the next statements. Even it jumps out of the &lt;code&gt;getPosts&lt;/code&gt; function.&lt;/p&gt;

&lt;p&gt;We can use other Web APIs like &lt;strong&gt;setTimeout&lt;/strong&gt;, and &lt;strong&gt;setInterval&lt;/strong&gt; to create timer functions that will run after a specified time period. Will run once in case of setTimeout and periodically in a loop in case of setInterval. We will not deep dive into them for now.&lt;/p&gt;

&lt;h2&gt;
  
  
  Callback functions
&lt;/h2&gt;

&lt;p&gt;The callback function is just a normal function that is passed to another function as an argument, and the execution of our callback function is handled inside and by the parent function.&lt;/p&gt;

&lt;p&gt;First of all, keep in mind that both the functions involved are just normal JavaScript functions. As functions are also objects like most of the stuff in JavaScript, we can pass them to other functions as arguments.&lt;/p&gt;

&lt;p&gt;Our callback function doesn’t get executed right away, but it is gonna sit and wait until parent functions call when it’s needed. This way we can separate some logic in a function and park it outside of the main execution thread. This way we can shift JavaScript from &lt;strong&gt;synchronous blocking&lt;/strong&gt; to asynchronous non-blocking.&lt;/p&gt;

&lt;p&gt;Here is a small catch. Callbacks function can be synchronous or asynchronous. Synchronous callback functions are invoked immediately inside outer functions, but asynchronous functions sit and wait until the specific condition(s) are fulfilled in the future.&lt;/p&gt;

&lt;p&gt;Consider this simple example, where we are passing the &lt;code&gt;greeting&lt;/code&gt; function as an argument to &lt;code&gt;processUserInput&lt;/code&gt; function. That is called when the user inputs his/her name in the prompt. Our callback function also accepts an argument (name), which is provided by an external function. Now, you need to guess, whether it is &lt;strong&gt;synchronous or asynchronous&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--gTn17kmS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3e9z5wz44sht6km21cl3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--gTn17kmS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3e9z5wz44sht6km21cl3.png" alt="Synchronous Callback function" width="880" height="510"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Of course, it is a synchronous callback function. Our callback function is being called immediately in the external function. Well, you might say the user will take some time entering the name, then how it is immediate execution? Well answer to this is very simple. The delay is from the user itself. If you see our program, there is no programmatic delay. As soon as there is an input, our program invokes the callback function.&lt;/p&gt;

&lt;p&gt;Let's make the above example asynchronous. Now we have added setTimeout Web API, which creates a timer function inside the browser and invokes our callback function after the 2-second mark.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--HT4HdBVg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p7k3b19eevmxlw2u4lic.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--HT4HdBVg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p7k3b19eevmxlw2u4lic.png" alt="Asynchronous Callback function" width="880" height="635"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is an example of the asynchronous callback function because we are parking our callback function using setTimeout Web API. I can prove it by the output of this program. When you run this program, you see;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;User {name} input&lt;/code&gt; → &lt;code&gt;setTimeout() executed&lt;/code&gt; → &lt;code&gt;Callback function bypassed&lt;/code&gt; → &lt;code&gt;2 Second Delay&lt;/code&gt; → &lt;code&gt;Hello, {name}&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;In traditional JavaScript, we used to handle our asynchronous logic using callback functions. This is the reason you might see some old StackOverflow answers(i often do need them 😆) using callback functions, and sometimes callback hells.&lt;/p&gt;

&lt;h3&gt;
  
  
  Callback Hell
&lt;/h3&gt;

&lt;p&gt;As we know, we pass the callback function to another function to complete its execution inside the parent function. What if we do not need our parent function to be called immediately, but inside another function? Well, another function. Is it a problem? Nope, it's totally fine.&lt;/p&gt;

&lt;p&gt;But what if we need to pass control of our second parent function to another function, by passing it to another function? Is it a problem now? It looks messy but no problem. I can handle it. Okay!!! fine.&lt;/p&gt;

&lt;p&gt;But what if…. Hey hey, stop 🛑. It is a problem. A big problem indeed. Give me the solution.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--8LP9dyEc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/91kyv2gpchrgtoo1no9k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--8LP9dyEc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/91kyv2gpchrgtoo1no9k.png" alt="Callback Hell" width="880" height="704"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The solution to this messy callback chaining was introduced in &lt;strong&gt;ECMAScript 2015(ES6)&lt;/strong&gt;. JavaScript introduced more descent and &lt;strong&gt;performant&lt;/strong&gt; way to handle asynchronous code in the form of promises.&lt;/p&gt;

&lt;h2&gt;
  
  
  JavaScript Promises
&lt;/h2&gt;

&lt;p&gt;The callback function approach is really effective in small programs, with up to 2 to 3 levels of chaining. But beyond that code becomes like a hell to read.&lt;/p&gt;

&lt;p&gt;JavaScript introduced a very cleaner, more performant, and more elegant way to handle asynchronous behavior in our code.&lt;/p&gt;

&lt;p&gt;Promises are JavaScript objects that can have one of the 3 possible states, depending upon the outcome of the promise.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;em&gt;Pending&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;Fulfilled&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;Rejected&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Promises in JavaScript are no different than promises we make in our life. Like real-world promises, JavaScript promises can be kept or rejected. You make a promise for something in the future, let's say you will quit smoking. With the passage of time, there are two possible scenarios;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A promise is fulfilled&lt;/strong&gt;: You successfully stand by your promise and the promise is kept. In the context of JavaScript promise, the promise object returns some data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Promise is rejected&lt;/strong&gt;: You are not able to fulfill your promise and get rid of the promise instead of smoking😍. In the context of JavaScript promise, on rejection, the promise returns some error.&lt;/p&gt;

&lt;p&gt;Hopefully, this far you understand the basic soul of Promises in JavaScript.&lt;/p&gt;

&lt;p&gt;I was reading the guide on Promises on &lt;a href="https://www.w3schools.com/"&gt;W3Schools&lt;/a&gt; and saw something really explanatory.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;“Producing code” is code that can take some time.&lt;/p&gt;

&lt;p&gt;“Consuming code” is code that must wait for the result.&lt;/p&gt;

&lt;p&gt;A Promise is a JavaScript object that links producing code and consuming code.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let me show you what this means with examples. You encounter &lt;strong&gt;two scenarios&lt;/strong&gt; while dealing with Promises in this world of JavaScript.&lt;/p&gt;

&lt;h3&gt;
  
  
  Creating Promise — “Producing code” is code that can take some time.
&lt;/h3&gt;

&lt;p&gt;Let's create a simple promise, that takes 2 seconds to complete and returns some data if resolved and an error if rejected. This is how we implement this;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--eNjvR2GJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7hd9k3lztnz9n3kptvrt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--eNjvR2GJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7hd9k3lztnz9n3kptvrt.png" alt="Promise create" width="880" height="588"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;What is happening here;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step1&lt;/strong&gt;: We create a new promise by using &lt;code&gt;new Promise()&lt;/code&gt; , and assigns it to &lt;code&gt;myBasicPromise&lt;/code&gt; variable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step2&lt;/strong&gt;: We are faking the time factor by 2 seconds by using setTimeout Web API, to pretend our promise actually took some time to complete.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step3&lt;/strong&gt;: After the 2-second mark, data is available(from API call, from a local file, etc.).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step4&lt;/strong&gt;: Hard part, we resolve or reject our promise based on performing checks on the data we retrieve.&lt;/p&gt;

&lt;p&gt;Keep one thing in mind that, when you are using JavaScript, you will rarely need to create promises, but consume in most cases. All of the latest libraries, modules, and features come with built-in a promise-based approach. Like, fetch API, &lt;strong&gt;axios&lt;/strong&gt; client, &lt;strong&gt;File API&lt;/strong&gt;, etc.&lt;/p&gt;

&lt;h3&gt;
  
  
  Consuming Promise — “Consuming code” is code that must wait for the result.
&lt;/h3&gt;

&lt;p&gt;Let's consume our promise. Wait. There are two approaches that we can use to consume promises.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;then()&lt;/code&gt; — &lt;code&gt;catch()&lt;/code&gt; methods&lt;br&gt;
&lt;code&gt;async&lt;/code&gt; / &lt;code&gt;await&lt;/code&gt; keywords&lt;br&gt;
Let's start with the first method.&lt;/p&gt;

&lt;h4&gt;
  
  
  Using then() catch() methods
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--rGO_elcy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x37vr22jo2kc2wjercy3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--rGO_elcy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x37vr22jo2kc2wjercy3.png" alt="Promise consume using then method" width="880" height="534"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;What is happening here;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step1&lt;/strong&gt;: If the promise was resolved(fulfilled) after checks we make on data, we get result inside &lt;code&gt;then()&lt;/code&gt; method. We can do anything with this response data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step2&lt;/strong&gt;: If the promise did not pass checks and was rejected, &lt;code&gt;then()&lt;/code&gt; method is skipped altogether and we catch errors inside &lt;code&gt;catch()&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;I have added the last console statement so you can see, that this statement will always run before the promise result or error. Shows us that promise runs asynchronously and doesn't block the preceding code. Well, there is another method attached to the promise object called &lt;code&gt;finally()&lt;/code&gt;. I forgot to add it in the screenshot. You can add it after the catch block, and it will always run when the promise has been settled(resolved or rejected.)&lt;/p&gt;

&lt;h4&gt;
  
  
  Using async / await keywords
&lt;/h4&gt;

&lt;p&gt;We can consume our promises using async await keywords as well. Here is how.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6QhnFN7q--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q7rapnmydv9lsnrd1n7z.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6QhnFN7q--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q7rapnmydv9lsnrd1n7z.png" alt="Promise consume using async await keywords" width="880" height="632"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step1&lt;/strong&gt;: We are wrapping our promise-consuming logic inside an &lt;code&gt;async&lt;/code&gt; function, so we can use &lt;code&gt;await&lt;/code&gt; keyword. Awaiting our promise object returns us results if the promise was fulfilled. This step is similar to using &lt;code&gt;then()&lt;/code&gt; method in the above approach.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step2&lt;/strong&gt;: But what if our promise was rejected? How do we catch error in this case? We can use JavaScript special &lt;code&gt;try{} catch{}&lt;/code&gt;. It will try to execute our promise, but will also catch any error which pops out during the process. Remember that, try{} catch{} blocks are not specific to promises, but they are general JavaScript features that we are using in this approach.&lt;/p&gt;

&lt;h4&gt;
  
  
  Promise Chaining
&lt;/h4&gt;

&lt;p&gt;Let's discuss the main reason, why we should use Promises over callback functions. Callback chaining(callback hell) was the main reason we adopted Promises, now we need to do the same thing in Promises.&lt;/p&gt;

&lt;p&gt;You can easily chain a series of actions simply by using multiple &lt;code&gt;then()&lt;/code&gt; methods. We will discuss the promise-based implementation of &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API"&gt;fetch API&lt;/a&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  Using chaining then() methods
&lt;/h4&gt;

&lt;p&gt;As you can see, we are not producing code here, meaning we are not creating a promise. We are just the consumers, as you will be in most of cases.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--OWuXTqDs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0egt1j05k7chhsjk5tzr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--OWuXTqDs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0egt1j05k7chhsjk5tzr.png" alt="Promise chaining using then" width="880" height="662"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;What is happening here;&lt;br&gt;
&lt;strong&gt;Step1&lt;/strong&gt;: We are fetching posts from JSON placeholder API. When we call &lt;code&gt;fetch(API_END_POINT)&lt;/code&gt;, it returns us a promise object. From here we can handle our promise by using the then() method.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step2— First then()&lt;/strong&gt;: We receive a response inside first then() block, when &lt;code&gt;fetch()&lt;/code&gt; promise, was &lt;code&gt;resolved&lt;/code&gt; — successfully fetched. We might encounter an error as well inside the catch() block, due network problem, or in case the server responds with the error.&lt;/p&gt;

&lt;p&gt;But why do we need chaining in this particular case? The reason is that fetch API returns the response object in the first place. But we need data instead. This response object, holds the &lt;code&gt;json()&lt;/code&gt; method inside its prototype(&lt;code&gt;__proto__&lt;/code&gt;) property. We call the json() method on the response object, which in turn returns use another promise. Which can be handled inside first then() block, or we can chain then() blocks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step3— Second then()&lt;/strong&gt;: Keep in mind that, this particular then() method is not attached to the main fetch() promise. But the promise returned by then() just behind it. Once &lt;code&gt;res.json()&lt;/code&gt; promise resolves, we get our data. We have retrieved our data, so need to further chain promise.&lt;/p&gt;

&lt;h5&gt;
  
  
  Chaining using async/await methods
&lt;/h5&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--i62gyD-T--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hlti7cbibdhb3ivdxnif.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--i62gyD-T--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hlti7cbibdhb3ivdxnif.png" alt="Promise chaining using async await keyword" width="880" height="548"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I am not going to explain this time. The guide's length has already grown more than I expected. I believe you already know it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;BONUS&lt;/strong&gt;&lt;br&gt;
As you can see, the &lt;code&gt;fetch()&lt;/code&gt; promise accepts an argument. So let me tell you, how you can pass arguments to your promise.&lt;/p&gt;

&lt;p&gt;Simply wrap your promise inside a function, and return the promise from it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--FK0QYK4l--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z9eoccdoozz1i73i7ld6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--FK0QYK4l--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z9eoccdoozz1i73i7ld6.png" alt="Promise Tip - how to pass arguments to promise" width="880" height="739"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Final Step
&lt;/h3&gt;

&lt;p&gt;To completely understand asynchronous code behavior in JavaScript we need to address the final question.&lt;/p&gt;

&lt;h2&gt;
  
  
  What are the microTask queue and the Callback queue in JavaScript?
&lt;/h2&gt;

&lt;p&gt;Well, to understand these concepts we need to know little about how the JavaScript engine executes asynchronous code. Whenever Promise, Web API, &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver"&gt;Mutation Observer&lt;/a&gt;, etc. are encountered inside our code. It is added to the Callstack. As we do not intend it to be executed right away, it creates a sort of timer function and pops out of the main execution stack.&lt;/p&gt;

&lt;p&gt;Once the timer function has expired, our callback function(function passed to &lt;code&gt;then()&lt;/code&gt; or function passed to &lt;code&gt;setTimeout()&lt;/code&gt;, etc.) is sent to one of the Callback queue or the microTask queue.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Callback functions from Promises, Mutation Observers, and fetch API has higher priority and goes to the microTask queue.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Ordinary callback functions from Web APIs like setTimeout, and setInterval go to the callback queue.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The MicroTask queue always has higher priority, and eventloop will always check for the callback queue once all of the callbacks from the microTask queue have been transferred to the Execution stack already.&lt;/p&gt;

&lt;p&gt;You can learn more about the MicroTask queue and the Callback queue from &lt;a href="https://www.geeksforgeeks.org/what-is-the-difference-between-microtask-queue-and-callback-queue-in-asynchronous-javascript/"&gt;this awesome article&lt;/a&gt; at &lt;a href="https://www.geeksforgeeks.org/"&gt;geeksforgeeks&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Wrapping Up
&lt;/h2&gt;

&lt;p&gt;Hopefully, you liked this guide, and let me know if something was confusing in this entire guide. If you find some mistake, please let me know. I would love to make the correction for future readers.&lt;/p&gt;

&lt;p&gt;I regularly post guides like this, about the &lt;strong&gt;MERN&lt;/strong&gt; stack. If this is your field of interest and want to read other guides like this, do follow me.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;See ya soon. Till then stay safe and try to keep others safe. ❤️&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>async</category>
      <category>beginners</category>
      <category>webdev</category>
    </item>
    <item>
      <title>SSR - SSG - ISR - CSR in Next.js - The Ultimate Guide</title>
      <dc:creator>Azhar Dev</dc:creator>
      <pubDate>Wed, 03 Aug 2022 09:42:00 +0000</pubDate>
      <link>https://dev.to/idrazhar/ssr-ssg-isr-csr-in-nextjs-the-ultimate-guide-256m</link>
      <guid>https://dev.to/idrazhar/ssr-ssg-isr-csr-in-nextjs-the-ultimate-guide-256m</guid>
      <description>&lt;p&gt;Are you a React lover? If you ask me, of course, I am a die-hard fan. Performance boost, &lt;a href="https://reactjs.org/docs/faq-internals.html" rel="noopener noreferrer"&gt;virtual DOM(vDOM)&lt;/a&gt;, and Components-based architecture were the major factors that convinced me to choose React.js over other awesome JavaScript frameworks in the market, like Angular and Vue. Without a doubt, the main reason users go for React is the performance boost it gives against traditional technologies. Without a debate, ReactJs is an awesome library that gives us a massive performance boost using vDOM and unlocking something called &lt;strong&gt;Client Side Rendering(CSR)&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;You might also have heard of &lt;a href="https://nextjs.org/" rel="noopener noreferrer"&gt;Next.js&lt;/a&gt;, of course. Next.js is basically the hottest React.js framework in the market right now. And my personal favorite as well. If you are coding in React for some time now, I bet you have heard of it and some lucky fellows might have tried it as well. Please let me know your experience in the comments section after reading this guide.&lt;/p&gt;

&lt;p&gt;Well, guys at Next.js claim that;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The React Framework for Production!&lt;br&gt;
Next.js gives you the best developer experience with all the features you need for production: hybrid static &amp;amp; server rendering, TypeScript support, smart bundling, route pre-fetching, and more. No config needed.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;After reading the above statement, a lot of questions arise in our minds, if nothing came to your mind, I am really sorry 😉.&lt;/p&gt;

&lt;p&gt;Questions like;&lt;br&gt;
&lt;strong&gt;Is NextJs better than Vanilla React?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;What does NextJs provides us, which ReactJs don't or can't?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;If React is a beast performance considering performance, why do we actually need NextJs?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You will get all of your answers in this guide. Just stay with me. We will answer these questions one by one.&lt;/p&gt;
&lt;h3&gt;
  
  
  Is NextJs better than React?
&lt;/h3&gt;

&lt;p&gt;Without a debate, NextJs has a significant edge over React in production. One of the reasons is obvious that it is an extension, a sort of wrapper of React. NextJs provides us with all the features of React and in addition unlocking some major features like &lt;strong&gt;Server Side Rendering(SSR)&lt;/strong&gt;, built-in API routes, automatic Code Splitting, assets optimization(fonts, images, etc.), &lt;strong&gt;pre-rendering&lt;/strong&gt;, and much more.&lt;/p&gt;

&lt;p&gt;The main focus of our today's tutorial would be pre-rendering in NextJs, different ways of pre-rendering, like &lt;strong&gt;Static Site Generation(SSG)&lt;/strong&gt;, Server Side Rendering(SSR), and something really cool, &lt;strong&gt;Incremental Static Regeneration(ISR)&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;ISR is basically an advanced version of SSG, which we can use to tackle &lt;strong&gt;stale&lt;/strong&gt;(outdated) data problems in SSG. We will discuss automatic ISR as well as how we can manually trigger revalidation. &lt;/p&gt;
&lt;h3&gt;
  
  
  What does NextJs provides us, that ReactJs do not or can not?
&lt;/h3&gt;

&lt;p&gt;As we have already discussed, NextJs provides us with all the features of React and in addition unlocking some major features like Server Side Rendering, built-in API routes, automatic Code Splitting, assets optimization, pre-rendering, Internationalization, and much more. For a complete reference, do visit the Next.js &lt;a href="https://nextjs.org/" rel="noopener noreferrer"&gt;homepage&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;
  
  
  If React is a beast, why do we need NextJs?
&lt;/h3&gt;

&lt;p&gt;Well, this important question needs to be answered in detail. We need to know how React.js works, and what improvements Next.js does bring to the table.&lt;/p&gt;
&lt;h4&gt;
  
  
  Working of React
&lt;/h4&gt;

&lt;p&gt;Before React, some smart minds at Facebook noticed that JavaScript was pretty fast but DOM manipulations were slowing everything down. DOM is basically an object-based representation of the Web page we are viewing. DOM is a set of nodes, every node refers to a particular element on the webpage. In short, DOM is a tree-like object-based representation of a document, which contains information about a particular element, styles associated with that element, the geometry of that element in the document, etc.&lt;/p&gt;

&lt;p&gt;Before React, when we needed to change something in a webpage (DOM - behind the scenes), the whole webpage was recreated. This was very unintelligent and expensive. So programmers at Facebook came up with a smart(actually genius) way of manipulating DOM.&lt;br&gt;
 &lt;br&gt;
The &lt;strong&gt;problem&lt;/strong&gt; was a recreation of the whole DOM when the small change was to be reflected on the webpage. &lt;/p&gt;

&lt;p&gt;And the &lt;strong&gt;solution&lt;/strong&gt; React.js brought was intelligent monitoring of the actual dom in form of virtual DOM(vDOM), and only updating necessary portions of the actual DOM in the best way possible.&lt;/p&gt;

&lt;p&gt;This gave a massive performance boost compared to traditional DOM manipulation techniques as well as modern React competitors like Angular and Vue.&lt;/p&gt;
&lt;h4&gt;
  
  
  Client Side Rendering (CSR)?
&lt;/h4&gt;

&lt;p&gt;React.js also unlocks Client Side Rendering. Let me explain What CSR is? And how React.js uses CSR to provide us with performant applications. When a user visits an application built with React, following processes occur behind the scenes;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxnsctl4vp65e3h6vdulv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxnsctl4vp65e3h6vdulv.png" alt="Client side rendering infographic"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;[Image copied from &lt;a href="https://medium.com/walmartglobaltech/the-benefits-of-server-side-rendering-over-client-side-rendering-5d07ff2cefe8" rel="noopener noreferrer"&gt;this&lt;/a&gt; awesome article by &lt;a href="https://medium.com/@lexgrigoryan" rel="noopener noreferrer"&gt;Alex Grigoryan&lt;/a&gt;]&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step1&lt;/strong&gt;: Almost empty response is sent to the client(browser), which is a minimal HTML document. This document has nothing in it except links to the JavaScript chunks sitting on the server. There is a little &lt;strong&gt;blink&lt;/strong&gt; of emptiness before the web page is fully visible because there is nothing to render, but an almost empty &lt;strong&gt;HTML document&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step2&lt;/strong&gt;: In the second step, the JavaScript bundle is downloaded from the server. Usually, a complete application bundle is downloaded unless manual code splitting(&lt;a href="https://reactjs.org/docs/code-splitting.html#reactlazy" rel="noopener noreferrer"&gt;&lt;code&gt;React.lazy()&lt;/code&gt;&lt;/a&gt;) is implemented.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step3&lt;/strong&gt;: Browser executes JavaScript (React), and renders(&lt;a href="https://reactjs.org/docs/react-dom-client.html#createroot" rel="noopener noreferrer"&gt;&lt;code&gt;createRoot(rootEl).render()&lt;/code&gt;&lt;/a&gt;) content to the screen. Populates empty HTML document containing root node. At this point, our page is completely visible and interactive.&lt;/p&gt;

&lt;p&gt;On the other hand, Next.js does these things a little differently. Here is how.&lt;/p&gt;
&lt;h3&gt;
  
  
  Working of Next.js (SSR)
&lt;/h3&gt;

&lt;p&gt;Next.js unlocks Server Side Rendering (SSR) for our applications. In vanilla React.js we can implement SSR components as well using something called &lt;a href="https://reactjs.org/docs/react-dom-server.html" rel="noopener noreferrer"&gt;ReactDomServer&lt;/a&gt;, but it requires a little extra configuration.&lt;/p&gt;

&lt;p&gt;In Next.js(SSR), a request is sent to the server for a specific page, instead of sending the whole JavaScript bundle to the client, the server itself takes responsibility of rendering the page for us.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgwoay952f301sj1vmqzh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgwoay952f301sj1vmqzh.png" alt="Server side rendering Infographic"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;[Image copied from &lt;a href="https://medium.com/walmartglobaltech/the-benefits-of-server-side-rendering-over-client-side-rendering-5d07ff2cefe8" rel="noopener noreferrer"&gt;this&lt;/a&gt; awesome article by &lt;a href="https://medium.com/@lexgrigoryan" rel="noopener noreferrer"&gt;Alex Grigoryan&lt;/a&gt;]&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step1&lt;/strong&gt;: First of all after the request hits the server from the client, it starts building an HTML document for us. These powerful servers with extremely fast internet (for instance &lt;a href="https://vercel.com/" rel="noopener noreferrer"&gt;Vercel&lt;/a&gt;) can do this task in &lt;strong&gt;milliseconds&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step2&lt;/strong&gt;: Freshly generated HTML page is sent back to the browser with some associated JavaScript necessary for the page. The browser takes the HTML document and displays it for us. At this point, the page is completely visible to the user. But unfortunately, users cannot interact with it. But here is another catch. This phase of numbness does not last any longer than a few milliseconds. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step3&lt;/strong&gt;: Then comes the hydration part, the browser downloads JavaScript from the server, and now Page is interactive as well.&lt;/p&gt;
&lt;h4&gt;
  
  
  Difference
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Page is visible faster in the case of Next.js than React.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;There is a little &lt;strong&gt;blink&lt;/strong&gt; in the case of React because an almost empty document is received by the browser at first. While in the case of Next.js fully rendered HTML document is sent to the browser, so no blink.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Server resource utilization&lt;/strong&gt; is usually high in the case of Next.js because the server is the one doing all of the heavy duty.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Overall performance&lt;/strong&gt; is high in the case of Next.js because only necessary stuff(automatic code splitting) is downloaded from the server instead of the complete application bundle as in React. Readymade page is sent, ready to render the page is sent to the browser.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;



&lt;p&gt;As it is evident now, Nextjs has an edge over React js in almost every aspect. So it is not even a debate. Enough of the comparisons, let's focus on our main topic for today.&lt;/p&gt;
&lt;h2&gt;
  
  
  What is pre-rendering?
&lt;/h2&gt;

&lt;p&gt;Next.js pre-renders every single page by default on the server. When a user requests a page from the server, a page is &lt;strong&gt;freshly built(SSR)&lt;/strong&gt; on the server or the page is already sitting on a server(&lt;strong&gt;SSG&lt;/strong&gt;), ready to be delivered to the browser. We will discuss all the possible scenarios. This technique adopted by Next.js, to send ready-made, &lt;strong&gt;ready-to-render&lt;/strong&gt; pages to the browser when requested is called pre-rendering.&lt;/p&gt;

&lt;p&gt;If you visit Next.js pages documentation, you will learn that Next.js pre-renders every page, by default. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;By default, Next.js pre-renders every page. This means that Next.js generates HTML for each page in advance, instead of having it all done by client-side JavaScript. Pre-rendering can result in better performance and SEO.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Next.js don't believe in Client Side Rendering, which puts everything on the user's CPU and internet to make our application run. Instead, Next.js handles rendering &lt;strong&gt;Server side&lt;/strong&gt;. Next.js pre-renders(pre-builds) every page in advance before it is sent to the browser(SSR), or even before the page is requested by the user(SSG).&lt;/p&gt;

&lt;p&gt;Next.js generates HTML documents for every page on the server in advance, associated with minimal JavaScript necessary for the page. Our web page is completely available to the browser as well as search engine crawlers. Which in turn gives us better SEO scores and performance.&lt;/p&gt;

&lt;p&gt;We need to address some questions that might have already popped into your head. Questions like;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How does Next.js handle pre-rendering pages? &lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;What types of pre-rendering are there in Next.js?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;When to use, what type of pre-rendering?&lt;/strong&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  How does Next.js handle pre-rendering pages?
&lt;/h3&gt;

&lt;p&gt;NextJs pre-renders every page by default. When we bootstrap the Next.js app, we get &lt;code&gt;/pages&lt;/code&gt; directory. Any file inside the &lt;code&gt;pages&lt;/code&gt; directory is mapped as a page if it default exports a function.&lt;/p&gt;
&lt;h4&gt;
  
  
  Create Next App
&lt;/h4&gt;

&lt;p&gt;Let's create an empty Next.js app using &lt;code&gt;create-next-app&lt;/code&gt;, so you can also follow along. Open your terminal, and run the following command;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx create-next-app@latest &amp;lt;app-name&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or with yarn&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn create next-app &amp;lt;app-name&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Do not get confused by &lt;strong&gt;npx&lt;/strong&gt; here, as npm and npx are two separate things. &lt;a href="https://www.npmjs.com/" rel="noopener noreferrer"&gt;npm&lt;/a&gt; is a package manager for &lt;a href="https://nodejs.org/" rel="noopener noreferrer"&gt;Node.js&lt;/a&gt;. While &lt;a href="https://www.npmjs.com/package/npx" rel="noopener noreferrer"&gt;npx&lt;/a&gt; is a package by npm, it can be used to run npm package binaries. &lt;/p&gt;

&lt;p&gt;After finished, open the directory in the code editor, and spin up the app in the dev environment by running &lt;code&gt;npm run dev&lt;/code&gt; or &lt;code&gt;yarn dev&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Our main focus will be on the pages directory, so open it. You will see:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;/pages/api&lt;/code&gt;: Next.js provides us a way to build API routes from within our Next.js app in the form of serverless functions. As Next.js is using Node.js behind the scenes. We will discuss this in a while.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;_app.js&lt;/code&gt;: This is pretty much the starting point of every page inside the page's directory. You can think of it as a wrapper for every page.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;index.js&lt;/code&gt;: This file represents the homepage of our application, which users will see the visiting the root of our application, let's say, &lt;a href="http://www.example.com/" rel="noopener noreferrer"&gt;www.example.com/&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Well, we can add new pages inside our application by simply default exporting a component from a file inside the pages directory. Let's say we want to create an about page for our application, simply add about.js inside the &lt;code&gt;/pages&lt;/code&gt; directory. Now you can visit your page at &lt;code&gt;localhost:3000/about&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6a2srlz2fpab8alyavoh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6a2srlz2fpab8alyavoh.png" alt="About page demo"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  What types of pre-rendering are there in Next.js?
&lt;/h3&gt;

&lt;p&gt;As we already know Next.js builds every page in advance before it is sent to the browser. But we can categorize pre-rendering on the base of the time when the page(HTML document) is built on the server.&lt;/p&gt;

&lt;p&gt;Next.js supports two kinds of pre-rendering at the moment. But we can leverage it to three as follows;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Server Side Rendering(&lt;strong&gt;SSR&lt;/strong&gt;)&lt;/li&gt;
&lt;li&gt;Static Site Generation(&lt;strong&gt;SSG&lt;/strong&gt;)&lt;/li&gt;
&lt;li&gt;Incremental Static Regeneration(&lt;strong&gt;ISR&lt;/strong&gt;) - SSG extension&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Server Side Rendering?
&lt;/h4&gt;

&lt;p&gt;If a page is being generated again and again on every request, then it is Server Side Rendering. SSR is a great option for applications that need to update the UI more frequently, like stock listing applications. The user comes to the page, the request is sent to the server. The server generates a fresh copy of the Webpage(&lt;strong&gt;HTML document&lt;/strong&gt;) and sends it to the client with minimal JavaScript associated with it.&lt;/p&gt;

&lt;p&gt;After the page has been painted(displayed) by the browser, the browser downloads JavaScript and makes the our page interactive. This is called hydration. I will not discuss hydration in detail here, but Hydration is basically a process when our browser downloads JavaScript from the server, and the page becomes interactive. You can learn about it more in this &lt;a href="https://github.com/vercel/next.js/discussions/22276" rel="noopener noreferrer"&gt;article&lt;/a&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  How to implement SSR in Next.js?
&lt;/h4&gt;

&lt;p&gt;Well, another plus point of Next.js is that it gives you complete control over your application and does not bind you to use SSR or SSG for your entire application. You are free to choose SSR or SSG for individual pages. Or even you can use SSR or SSG on some portion of your page and then use Client Side Rendering(CSR) at runtime to handle the rest of the page. We will discuss these use cases in a while. For now, let's see how we can enable SSR for any page in Next.js.&lt;/p&gt;

&lt;p&gt;Consider this home page, fetching and listing fresh stock quotes every time this page is requested;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step1&lt;/strong&gt;: Replace the content of the homepage &lt;code&gt;/pages/index.js&lt;/code&gt; as;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0zbwm9dg9v0j9n1tojhk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0zbwm9dg9v0j9n1tojhk.png" alt="Homepage with initial content"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;By default, Next.js pre-renders this page via the Static Site Generation(SSG) technique. If we need to enable SSR on this page, there is only one thing we need to do. I mean this is the beauty of Next.js. We enable Server Side Rendering by just exporting a special function &lt;code&gt;getServerSideProps&lt;/code&gt; from our page.&lt;/p&gt;

&lt;h4&gt;
  
  
  getServerSideProps
&lt;/h4&gt;

&lt;p&gt;This is a special function provided by Next.js to unlock SSR for our page. If our page is exporting this function, the server will pre-render our page prior to sending out the page to the client. This function runs on every page request received by the server. If this page is requested by a transition in our page via &lt;code&gt;next/link&lt;/code&gt; our &lt;code&gt;next/router&lt;/code&gt;, an API request is sent to the server which triggers &lt;code&gt;getServerSideProps&lt;/code&gt;. Head over to this page to see the complete &lt;a href="https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props" rel="noopener noreferrer"&gt;getServerSideProps API&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step2&lt;/strong&gt;: Export the async function getServerSideProps from our application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step3&lt;/strong&gt;: Fetch fresh data from a data source(&lt;strong&gt;API&lt;/strong&gt;, database), and return an object containing props as a key.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fca2gpopmh5y8bivv8j0t.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fca2gpopmh5y8bivv8j0t.png" alt="Homepage getServerSideProps"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;By doing these simple steps, we have implemented SSR in our application. We will now receive our data inside the props object of our page. As &lt;code&gt;getServerSideProps&lt;/code&gt; runs, every time page is requested, we get fresh data from our data source. And every time up-to-date data is displayed on the webpage.&lt;/p&gt;

&lt;h3&gt;
  
  
  Static Site Generation (SSG)
&lt;/h3&gt;

&lt;p&gt;The second and recommended form of pre-rendering is Static Site Generation. As evident from the name, it is the best use case for static web pages which can be built before request.&lt;/p&gt;

&lt;p&gt;In the case of SSG, pages are built on build time when we build a site using &lt;code&gt;next build&lt;/code&gt; on the server. These pre-built pages sit on the server and once a request is received, these pre-built pages(HTML document and minimal JavaScript associated) are sent to the browser. Once the page has been painted in the browser, JavaScript is downloaded and the page becomes interactive after &lt;strong&gt;hydration&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Pages built with SSG can also be cached via &lt;strong&gt;CDN&lt;/strong&gt; unlike pages built using SSR. So response time is significantly low compared to SSR. Gives better performance and SEO score.&lt;/p&gt;

&lt;h4&gt;
  
  
  How to implement SSG in Next.js?
&lt;/h4&gt;

&lt;p&gt;Well, Next.js by default pre-renders pages statically using SSG. So no extra configuration like getServerSideProps (in case of SSR) is needed if your page doesn't depend on external data. Well, we can pretty much encounter three scenarios while statically generating pages in Next.js.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scenario1&lt;/strong&gt;: No need for external data while building a page on the server. If you are building some static website like a portfolio website, Guide, or Documentation site, usually(not always) you do not require any external data.&lt;/p&gt;

&lt;p&gt;In that case, you can simply default export your React component from the page file and you are good to go. Simply like this.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fad1ye0k0hijza9o5gjiy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fad1ye0k0hijza9o5gjiy.png" alt="SSG scenario 1: no need of data"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scenario2&lt;/strong&gt;: Your page needs some external data to be built on the server. Well, if you are building some product listing page or any page that needs data from an external source to be properly built on the server. Consider this about page, which needs to fetch team members from some &lt;strong&gt;database&lt;/strong&gt;. Of course, the server cannot build a page without data being available first.&lt;/p&gt;

&lt;p&gt;How do we handle this case? Don't worry, it's not difficult. Next.js provides us with another special function named &lt;code&gt;getStaticProps&lt;/code&gt;. We can simply export it from our page and fetch data in it prior to pre-rendering.&lt;/p&gt;

&lt;h5&gt;
  
  
  getStaticProps
&lt;/h5&gt;

&lt;p&gt;It is a special function, provided by Next.js to help us fetch data prior to pre-rendering. This function runs on the server, so not included in the client-side bundle. It runs before building the page and passes data to the page via &lt;strong&gt;props&lt;/strong&gt;. Head over to this page to see the complete &lt;a href="https://nextjs.org/docs/basic-features/data-fetching/get-static-props" rel="noopener noreferrer"&gt;getStaticProps API&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7su0cw4xu9t8xstjpagw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7su0cw4xu9t8xstjpagw.png" alt="SSG scenario 2: need external data"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scenario3&lt;/strong&gt;: Your page is dynamically generated, and your page also requires data from some external data source. Consider the case of a blog or e-commerce website. Where you cannot create an individual page for every blog post or product inside your page's directory. You need some more automated way to accomplish this task. Let me show you how you can handle this case in Next.js using SSG.&lt;/p&gt;

&lt;p&gt;We are going to use something called dynamic routes in Next.js. We will move forward with a blog example.&lt;/p&gt;

&lt;h4&gt;
  
  
  Implementing Dynamic Route
&lt;/h4&gt;

&lt;p&gt;In Next.js, we can create a dynamic route with a special syntax. We need to add &lt;code&gt;/pages/blog&lt;/code&gt; directory, inside that we need  tocreate two files; &lt;code&gt;index.js&lt;/code&gt; for posts archive and &lt;code&gt;[slug].js&lt;/code&gt; for individual post pages.&lt;/p&gt;

&lt;p&gt;With syntax done, any path after &lt;code&gt;localhost:3000/blog/&lt;/code&gt; will be available to us for use inside &lt;code&gt;[slug].js&lt;/code&gt; via &lt;strong&gt;router&lt;/strong&gt; object. I will show you in a while. I will show you in a while. You can learn more about dynamic routes over &lt;a href="https://nextjs.org/docs/routing/dynamic-routes" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  Fetching data for a specific post using slug parameter
&lt;/h4&gt;

&lt;p&gt;I believe you have already guessed it. We will simply export &lt;code&gt;getStaticProps&lt;/code&gt; from our file. But this time, the requirements are a bit different. Last time we knew what exactly to get from the data source.&lt;/p&gt;

&lt;p&gt;This time, it's a dynamic route. Actually, we need to fetch data from the server based on a slug. Like in this case &lt;code&gt;/blog/post-1&lt;/code&gt; we need to fetch post with &lt;code&gt;slug=post-1&lt;/code&gt; and in case of &lt;code&gt;/blog/some-other-post-slug&lt;/code&gt; out slug would be different. &lt;code&gt;some-other-post-slug&lt;/code&gt; exactly.&lt;/p&gt;

&lt;p&gt;Next.js makes our work a bit easy and provides us what is the slug of the requested page inside &lt;code&gt;getStaticProps&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8mt0d74sby7je3ra0etw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8mt0d74sby7je3ra0etw.png" alt="Post page 1"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Add getStaticProps to fetch specific post by slug;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjqvgodmz9jwjrvvctky9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjqvgodmz9jwjrvvctky9.png" alt="Post page 1"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once a post has been fetched we are passing that data to the PostPage component as props. We are checking if the post is not defined, and we are returning a &lt;code&gt;notFound=true&lt;/code&gt; This will ensure a 404 page appears if the post was not there.&lt;/p&gt;

&lt;p&gt;Well, you might be thinking, that's it like previous cases. But it is not the case this time. Because we are pre-rendering blog posts dynamically. Now think about it, how would Next.js know which blog posts to pre-render? There could be many blog posts and we want to pre-render all of them. The answer is we need to tell Next.js that, these are the routes(slugs), that needed to be pre-rendered.&lt;/p&gt;

&lt;p&gt;What Next.js would do is, just run getStaticProps props for every slug we will provide. It will fetch data from the data source and pre-renders page for us. Now the question is how do we tell Next.js, which routes to pre-render?&lt;/p&gt;

&lt;p&gt;This is very simple, as Next.js provides us with another special function called &lt;code&gt;getStaticPaths&lt;/code&gt; that we need to export from the dynamic route page &lt;code&gt;[slug].js&lt;/code&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  getStaticPaths
&lt;/h4&gt;

&lt;p&gt;&lt;code&gt;getStaticPaths&lt;/code&gt; is a special function provided by Next.js. It runs on the server only, so addition  to the client bundle. This function runs only once on the server to supply Next.js with the list of paths that need to be pre-rendered. Head over to this page to see the complete &lt;a href="https://nextjs.org/docs/basic-features/data-fetching/get-static-paths" rel="noopener noreferrer"&gt;getStaticPaths API&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Simply export the async function getStaticPaths from our file. Now logic from here may with your use case. But let me tell you, what you have to do actually.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step1&lt;/strong&gt;: Fetch all posts of just slugs(if query filtering is available in your use case)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step2&lt;/strong&gt;: Format slugs or posts to a specific pattern. Where paths is an array of objects, each object containing single key named params, with an object as the value. This object contains the key named after the query parameter you used in the dynamic route file name. In my case, it is &lt;code&gt;slug&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;See the below example.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvvnqf9rwrm01gpracu37.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvvnqf9rwrm01gpracu37.png" alt="Post page 3"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you followed along, you have successfully implemented Static Site Generation in case of dynamic routes using getStaticProps and getStaticPaths.&lt;/p&gt;

&lt;h4&gt;
  
  
  Caveats in Static Site Generation(SSG)
&lt;/h4&gt;

&lt;p&gt;So far we know that pages generated using the SSG technique give us better performance and high SEO scores. Also, pages built with SSG can be cached via &lt;strong&gt;CDN&lt;/strong&gt; so users can get responses even faster. These are all the plus points of SSG. But there is a catch here. &lt;/p&gt;

&lt;p&gt;We know that pages are built at build time in SSG. But what if a user is accessing the page after several months? What if data on the CMS has changed? Admin has made some updates. What data would be displayed on our page? Same outdated data, right?&lt;/p&gt;

&lt;p&gt;This behavior is not needed in a few cases, where data gets updated more often. How Next.js handles this case scenario. Well, I am going to introduce &lt;strong&gt;Incremental Static Regeneration(ISR)&lt;/strong&gt; to you. I have recently built my personal blog using Next.js. And it is also using Incremental Static Regeneration.&lt;/p&gt;

&lt;h3&gt;
  
  
  Incremental Static Regeneration(ISR)
&lt;/h3&gt;

&lt;p&gt;ISR is an awesome technique introduced by Next.js to tackle &lt;strong&gt;stale or outdated&lt;/strong&gt; pages problems in Static Site Generation. It is not another kind of pre-rendering technique but an extension of SSG actually. &lt;/p&gt;

&lt;p&gt;You need to know what we are actually trying to solve here. We want our webpage to show updated content when we update data in the backend. When data you updated data in the backend, probably CMS, then you have 3 ways to update content on the Frontend (Next.js).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Method1(NOT RECOMMENDED)&lt;/strong&gt;: You can re-build your entire application(excluding cache) again when you need your page or pages to show updated data. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Method2&lt;/strong&gt;: You can use &lt;strong&gt;periodic&lt;/strong&gt; ISR (I named it myself 😍). &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Method3&lt;/strong&gt;: Or you can use &lt;strong&gt;on-demand&lt;/strong&gt; ISR. &lt;/p&gt;

&lt;p&gt;We will discuss both of these. Let's start with periodic ISR.&lt;/p&gt;

&lt;h4&gt;
  
  
  Periodic Incremental Static Regeneration
&lt;/h4&gt;

&lt;p&gt;This type of ISR automatically &lt;strong&gt;rebuilds&lt;/strong&gt; our page(not the entire application) after a &lt;strong&gt;specified time&lt;/strong&gt; period, when a request comes after that specified period.&lt;/p&gt;

&lt;p&gt;Let me explain. When users land on the page, a counter starts. Our user is seeing our cached version of the webpage. So performance factor is not affected. Our user gets the same page that a user would get if ISR is not implemented. &lt;/p&gt;

&lt;p&gt;When a counter hits our specified time, a request is sent to the server to rebuild the page. Everything is happening behind the scenes, in the background. Any request after our specified time, Next.js serves the &lt;strong&gt;newly built page&lt;/strong&gt;. And this freshly prepared page is &lt;strong&gt;cached&lt;/strong&gt; again. Again the cycle begins. &lt;/p&gt;

&lt;p&gt;Let me show you periodic ISR in action;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frli4a0072rd1sauhit5j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frli4a0072rd1sauhit5j.png" alt="periodic ISR"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You just need to add revalidate prop inside the getStaticProps function of your &lt;code&gt;[slug].js&lt;/code&gt; file. Next.js will try to revalidate(rebuild) our app when a request comes in after 60 seconds.&lt;/p&gt;

&lt;p&gt;Mean, for the first minute out user will see, the same cached version of our page and any request coming after one minute window will trigger revalidation on the server. Next.js will rebuild the page in the background. If a page was built successfully, Next.js will invalidate the cache and show an updated page afterward.&lt;/p&gt;

&lt;p&gt;[&lt;strong&gt;NOTE:&lt;/strong&gt; 60seconds is too aggressive. Your server resources will be under fire when it needs to rebuild your page every minute(at most), Either you should use on-demand ISR or keep time as high as possible.]&lt;/p&gt;

&lt;h4&gt;
  
  
  On-demand Incremental Static Regeneration
&lt;/h4&gt;

&lt;p&gt;I personally like this type of ISR, because you have kinda more control over revalidation. You decide when you want to revalidate your page. Your server resources are safe. This also minimizes the period, when users need to see outdated pages.&lt;/p&gt;

&lt;p&gt;To implement on-demand Incremental Static Generation, we simply need to create an API route, which we can later call to revalidate particular paths.&lt;/p&gt;

&lt;p&gt;I hope you already know how to create API routes in Next.js. But if not, I will explain in a beginner-friendly manner. Or you can simply head over to this &lt;a href="https://nextjs.org/docs/api-routes/introduction" rel="noopener noreferrer"&gt;guide&lt;/a&gt; to have a sneak peek.&lt;/p&gt;

&lt;h4&gt;
  
  
  Implementing revalidate API route
&lt;/h4&gt;

&lt;p&gt;We do not need to provide extra revalidate prop inside getStaticProps. So make sure to remove what (revalidate: 60) we added in the previous example.&lt;/p&gt;

&lt;p&gt;Let's create our API route. Add file inside the &lt;code&gt;/pages/api&lt;/code&gt; directory. In Next.js file added inside the &lt;code&gt;/pages/api&lt;/code&gt; directory is mapped as an API route, and can be accessed at &lt;code&gt;localhost:3000/api/some-route&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl3hq793s516voo12s4gy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl3hq793s516voo12s4gy.png" alt="on-demand isr basic handler"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We have added a basic handle for our route. You can test this by running running &lt;code&gt;localhost:3000/api/revalidate&lt;/code&gt;. You should get a JSON response back.&lt;/p&gt;

&lt;p&gt;Let's configure our handler to revalidate our page.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgo8oah37pw3td7iy40b7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgo8oah37pw3td7iy40b7.png" alt="on-demand isr main logic"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step1&lt;/strong&gt;: Grab the &lt;strong&gt;token&lt;/strong&gt; and &lt;strong&gt;route&lt;/strong&gt; from our request. While trying to revalidate, we would need to provide the route we want to revalidate and a secret token(prevent unauthorized requests) inside the request URL.&lt;/p&gt;

&lt;p&gt;Our sample request look will look like this;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In production&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;GET https://&amp;lt;your-site.com&amp;gt;/api/revalidate?secret=&amp;lt;token&amp;gt;&amp;amp;route=&amp;lt;route&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;In Development&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;GET http://localhost:3000/api/revalidate?secret=&amp;lt;token&amp;gt;&amp;amp;route=&amp;lt;route&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So first thing first, let's add our secret token inside the &lt;code&gt;.env.local&lt;/code&gt; file. This is the place where we can store our environment variables in Next.js.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkq4iziehfebgid1qoinw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkq4iziehfebgid1qoinw.png" alt="Adding secret to .env.local file"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Kill and restart your development server. You should be able to see environment variables loaded message in the console.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step2&lt;/strong&gt;: Secondly we need to do certain checks. First of all, if a token is not defined or the token inside the request and the one inside &lt;code&gt;.env.local&lt;/code&gt; does not match. Return server error with status code &lt;strong&gt;401&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Secondly, if the route is not defined, we need to return the very same response but with a different message.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step3&lt;/strong&gt;: Inside &lt;code&gt;try catch&lt;/code&gt; block, we try to invalidate our route by calling &lt;code&gt;res.revalidate(route)&lt;/code&gt; method. And once it is done we return a successful response. If any exception(error) occurs, we catch it and return an error response with a status code of &lt;strong&gt;500&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;That is it for revalidate API handler. Now our API route should be working fine. Time to test it out.&lt;/p&gt;

&lt;h4&gt;
  
  
  Testing
&lt;/h4&gt;

&lt;p&gt;Open your browser and enter make a request to the following endpoint;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;http://localhost:3000/api/revalidate?secret=&amp;lt;token&amp;gt;&amp;amp;route=&amp;lt;route&amp;gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Replace &lt;code&gt;&amp;lt;token&amp;gt;&lt;/code&gt; with your own secret token inside &lt;code&gt;.env.local&lt;/code&gt; and replace &lt;code&gt;&amp;lt;route&amp;gt;&lt;/code&gt; with your slug prefixing with &lt;code&gt;/blog/&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;For instance, if you want to revalidate &lt;code&gt;/post-1&lt;/code&gt; and your token is &lt;code&gt;123456789&lt;/code&gt;. Then your request should look like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;http://localhost:3000/api/revalidate?secret=123456789&amp;amp;route=/blog/post-1 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you get success response, with &lt;code&gt;revalidated=true&lt;/code&gt; . You have successfully revalidated your page.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxqhte9dbn7vhr3ieyt5b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxqhte9dbn7vhr3ieyt5b.png" alt="on-demand ISR response"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusions
&lt;/h3&gt;

&lt;p&gt;In this guide we have learned;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;What is Client Side Rendering and how does React.js use it?&lt;/li&gt;
&lt;li&gt;Why do we need to use Next.js instead of React.js in production?&lt;/li&gt;
&lt;li&gt;What is pre-rendering and how does Next.js handles pre-rendering our pages?&lt;/li&gt;
&lt;li&gt;How many kinds of pre-rendering are supported in Next.js?&lt;/li&gt;
&lt;li&gt;How to unlock Server Side Render your pages in Next.js on every request(SSR)?&lt;/li&gt;
&lt;li&gt;How to statically generate web pages in Next.js at build time(SSG)?&lt;/li&gt;
&lt;li&gt;How to solve stale data problems in pages build with SSG using Incremental Static Regeneration?&lt;/li&gt;
&lt;li&gt;How to periodically revalidate your pages, and how to implement on-demand Incremental Static Regeneration?&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Wrapping Up
&lt;/h3&gt;

&lt;p&gt;Hopefully, you liked this guide, and let me know if something was confusing in this entire guide. If you find some mistake, please let me know. I would love to make the correction for future readers.&lt;/p&gt;

&lt;p&gt;I regularly post guides like this revolving around the &lt;strong&gt;MERN&lt;/strong&gt; stack. If that is your field of interest and want to read other guides like this, do follow me.&lt;/p&gt;

&lt;p&gt;See ya soon. Till then stay safe and try to keep others safe. ❤️&lt;/p&gt;

</description>
    </item>
    <item>
      <title>0 to 1 - How JavaScript works under the hood (Part 2)</title>
      <dc:creator>Azhar Dev</dc:creator>
      <pubDate>Fri, 22 Jul 2022 06:51:49 +0000</pubDate>
      <link>https://dev.to/idrazhar/0-to-1-how-javascript-works-under-the-hood-part-2-48l5</link>
      <guid>https://dev.to/idrazhar/0-to-1-how-javascript-works-under-the-hood-part-2-48l5</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--oUACVj8U--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uncdqdcvxjqnihaz5gku.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--oUACVj8U--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uncdqdcvxjqnihaz5gku.jpg" alt="Cover image - JavaScript is everywhere" width="744" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hi, welcome back.&lt;/p&gt;

&lt;p&gt;If you are coming from part one of this guide you will find this part a breeze. But if not, I will strongly recommend you to check out &lt;a href="https://dev.to/idrazhar/0-to-1-series-how-javascript-works-under-the-hood-157f"&gt;Part 1&lt;/a&gt; which serves as a base for this guide. But you can also read and gain something from this article alone. This guide is completely independent of the previous one.&lt;/p&gt;

&lt;h3&gt;
  
  
  So far we have learned in Part 1
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;A little history of JavaScript&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;JavaScript Runtime&lt;/strong&gt;, which is basically a special environment provided by the browser or context we run our code in. This environment provides us with objects, APIs, and other components so our code can interact with the outside world and get executed.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Components of runtime environment&lt;/strong&gt;; like JavaScript engine, Web APIs, Callback queue, and Eventloop.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;JavaScript engine&lt;/strong&gt;, which again consists of Callstack or Execution Stack and the Heap.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Execution Context&lt;/strong&gt;, which is basically a special environment for the execution of JavaScript code, contains the code that is currently running and everything that aids in its execution. This special environment is called the Execution context. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Scoping and Temporal Dead Zone&lt;/strong&gt;, we learned how functions can access declarations from their parent scope via &lt;strong&gt;Lexical Scoping&lt;/strong&gt;. We briefly discussed TDZ as well.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this article, we will be focussing more on the remaining three major components of JavaScript runtime in the context of the browser;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Web APIs&lt;/li&gt;
&lt;li&gt;Callback queue&lt;/li&gt;
&lt;li&gt;The Eventloop&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  The drawback of JS single-threaded nature
&lt;/h3&gt;

&lt;p&gt;As we all know JavaScript is single-threaded in nature, as it has only one heap and one stack. The next program has to sit and wait until the current program finishes execution, heap, and Callstack get cleared and the new program starts executing.&lt;/p&gt;

&lt;p&gt;But what if, the currently executing task is taking so long, what if our current execution context is requesting some data from the server(slow server), definitely it would take some time. In this case, the Callstack queue will be &lt;strong&gt;stuck&lt;/strong&gt; as JavaScript only executes one task at a time. All the execution contexts that are next to be executed will keep waiting until our current guilty Execution context is resolved. How we can handle this sort of behavior. How can we schedule some tasks, or park some expensive tasks so that we can keep our application going? How can we make our &lt;strong&gt;synchronous&lt;/strong&gt; JavaScript &lt;strong&gt;asynchronous&lt;/strong&gt;? &lt;/p&gt;

&lt;p&gt;This is where &lt;strong&gt;Web APIs&lt;/strong&gt;, &lt;strong&gt;Callback queue&lt;/strong&gt;, and &lt;strong&gt;Eventloop&lt;/strong&gt; come to the rescue.&lt;/p&gt;

&lt;h2&gt;
  
  
  Web APIs
&lt;/h2&gt;

&lt;p&gt;First of all, we should know that Web APIs are not part of the JavaScript engine, but they are part of Web browsers. They provide our code with some extra features so our code can interact with the outside world. Modern web browsers have a lot of web APIs which we can use in our applications. We often use web APIs to carry out these noble purposes in our application:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Dom Manipulation&lt;/strong&gt;: Probably the most commonly used web API among JavaScript developers is the &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model"&gt;DOM API&lt;/a&gt; which enables us to manipulate DOM and CSS styles associated with DOM elements. It gives us the power to add nodes to DOM, remove them or apply styles to them dynamically.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Graphics Manipulations&lt;/strong&gt;: Web APIs like &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API"&gt;Canvas API&lt;/a&gt; and &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API"&gt;Web Graphics Library API&lt;/a&gt; let you draw and manipulate graphics in the canvas element. They let you programmatically add or modify graphics. The Canvas API provides a means for drawing graphics via JavaScript and the HTML &lt;code&gt;&amp;lt;canvas&amp;gt;&lt;/code&gt; element. Among other things, it can be used for animation, game graphics, &lt;strong&gt;data visualization&lt;/strong&gt;, photo manipulation, and real-time video processing. The Canvas API largely focuses on 2D graphics.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Asynchronous JavaScript&lt;/strong&gt;: As we already know originally JavaScript is single-threaded synchronous in nature. But we can make it asynchronous with Web APIs like &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest"&gt;XMLHttpRequest&lt;/a&gt; and its promise-based replacement, the &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API"&gt;Fetch API&lt;/a&gt;. We can enable our JavaScript code to carry out other vital tasks until a response from the server is returned. We will talk about asynchronous JavaScript more in a while. For now, let's just move forward.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Work with Multimedia&lt;/strong&gt;:  Web APIs like &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API"&gt;Audio API&lt;/a&gt; and &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement"&gt;HTMLMediaElement&lt;/a&gt; provide us control over audio and video on the web. We can pause, play, forward our media or add certain effects to the stream.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Work with Files&lt;/strong&gt;: The &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/File"&gt;File API&lt;/a&gt; enables web applications to access files and their contents. Web applications can access files when the user makes them available, either using a file &lt;code&gt;&amp;lt;input&amp;gt;&lt;/code&gt; element or via drag and drop.&lt;/p&gt;

&lt;p&gt;All of the event listeners, AJAX calls, and timer functionalities sit in the Web APIs container until an event is triggered.&lt;/p&gt;

&lt;p&gt;Before deep diving into the &lt;strong&gt;Callback queue&lt;/strong&gt;, we should first discuss Callback functions.&lt;/p&gt;

&lt;h3&gt;
  
  
  What are Callback functions?
&lt;/h3&gt;

&lt;p&gt;The callback function is a normal function provided as an argument to another normal function, waiting to be called inside the recipient function at a suitable time.&lt;/p&gt;

&lt;p&gt;Let me explain it to you. The callback is not a special kind of function. It's just a normal function that is passed to some other function, and that function handles the invocation (calling) of our callback function. See this Callback function supplied to click eventlistner;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--lGj0xy6E--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5om7jc7lnarvrqvel7ea.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--lGj0xy6E--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5om7jc7lnarvrqvel7ea.png" alt="Callback function supplied to eventlistner" width="740" height="253"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you can see we are providing a callback function to the listener. This function is not called right away but when a click happens. So the callback function is sitting and waiting somewhere in the JavaScript engine for its trigger. When a user interacts and clicks, this function gets called. So the place where this function is sitting and waiting is the &lt;strong&gt;Callback queue&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;At first callback functions were used to handle asynchronous tasks in JavaScript. They did pretty well but handling more complex became like a hell. Because when a callback function is also an asynchronous function and receives another callback, syntax became really messy which we call &lt;strong&gt;The Callback Hell&lt;/strong&gt; these days.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Cei89j32--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dqeb9rcff0xl5uwrh8ht.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Cei89j32--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dqeb9rcff0xl5uwrh8ht.png" alt="Callback hell" width="740" height="337"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Well, that is not our topic for today, you can check out callbacks &lt;a href="https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Callback Queue
&lt;/h2&gt;

&lt;p&gt;The callback is a data structure that holds callback functions sent by Web APIs. Callback functions sit here until the Callstack is empty, and the &lt;strong&gt;Eventloop&lt;/strong&gt; transfers them to Callstack.&lt;/p&gt;

&lt;p&gt;As we all know JavaScript is a single-threaded synchronous language natively, and It runs your pieces of code sequentially. Line after line. If Line 13 is taking longer than expected, our program would freeze and would not attempt to execute Line 14 until 13 is completed. This is the problem that the Callback queue solves. Have a look at this setTimeout Web API:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--XkYdvmeP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y5j89fmu7rxagxz7rodx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--XkYdvmeP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y5j89fmu7rxagxz7rodx.png" alt="Callback queue with setTimeout API" width="663" height="289"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;setTimeout Web API executes a provided callback function after specified time. Learn more about of setTimeout &lt;a href="https://www.w3schools.com/jsref/met_win_settimeout.asp"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If we consider JavaScript as a &lt;strong&gt;single-threaded&lt;/strong&gt;, &lt;strong&gt;synchronous&lt;/strong&gt; programming language what output we would expect from this above code:&lt;/p&gt;

&lt;h4&gt;
  
  
  Expected
&lt;/h4&gt;

&lt;p&gt;First of all, &lt;code&gt;1&lt;/code&gt; will be logged to the console as a result of &lt;code&gt;console.log(1)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Then, after waiting for 1 second (1000ms), the callback function will be executed logging &lt;code&gt;2&lt;/code&gt; to the console. &lt;/p&gt;

&lt;p&gt;And finally, the program will end after logging &lt;code&gt;3&lt;/code&gt; to the console as a result of &lt;code&gt;console.log(3)&lt;/code&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Output
&lt;/h4&gt;

&lt;p&gt;First of &lt;code&gt;1&lt;/code&gt; logs as expected. &lt;/p&gt;

&lt;p&gt;Unexpectedly, &lt;code&gt;3&lt;/code&gt; logs to the console next. Apparently, the JavaScript engine skipped &lt;strong&gt;setTimeout&lt;/strong&gt; and moved on to the third statement &lt;code&gt;console.log(3)&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Then after &lt;code&gt;1&lt;/code&gt; second &lt;code&gt;2&lt;/code&gt; logs to the console.&lt;/p&gt;

&lt;h4&gt;
  
  
  Explanation
&lt;/h4&gt;

&lt;p&gt;Let me explain this behavior; at first, JavaScript encountered the &lt;code&gt;console.log()&lt;/code&gt; function and stored it in the Execution stack or Callstack for execution. Functional Execution Context(&lt;strong&gt;FEC&lt;/strong&gt;) gets created to execute this special built-in function(method), and it gets executed and fades out of the Callstack.&lt;/p&gt;

&lt;p&gt;Secondly, as a second statement, the JavaScript engine encounters setTimeout Web API. As we all know, setTimeout is not a feature of JavaScript itself. First of all, setTimeout is added to Callstack. But it is not executed here, being a web API, it creates a task inside the browser and pops out of the Callstack.&lt;/p&gt;

&lt;p&gt;JavaScript engine keeps executing code, again encounters &lt;code&gt;console.log(3)&lt;/code&gt; function and creates Functional Execution Context to handle it. Very similar to statement 1 &lt;code&gt;console.log(1)&lt;/code&gt; it gets executed and as a result, pops out of the main Execution stack.&lt;/p&gt;

&lt;p&gt;After the specified time in setTimeout API, which in our case is &lt;strong&gt;1000ms&lt;/strong&gt;, the browser sends this task(our callback function) to the &lt;strong&gt;callback queue&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;At this point Execution Context is empty, and our callback function is sitting in the Callback queue waiting for the opportunity of execution. Here a very important question arises, What next, and What connects the callback queue and the Callstack? You guessed it right, the &lt;strong&gt;event loop&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Eventloop
&lt;/h2&gt;

&lt;p&gt;The event loop is a special mechanism in JavaScript which keeps an eye on the Callstack and the Callback Queue. Its main purpose is to transport callback functions from the Callback queue to the Callstack for execution, once it is empty.&lt;/p&gt;

&lt;p&gt;The Callback queue works in a &lt;strong&gt;FIFO&lt;/strong&gt;(first in, first out) manner. Mean the oldest callback will be sent to the Callstack first. You can imagine the Callback queue simply as an array, which adds new callbacks with &lt;code&gt;Array.push()&lt;/code&gt; method to the end of the queue and takes the first callback out using &lt;code&gt;Array.shift()&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;The event loop takes callbacks from the callback queue &lt;strong&gt;one by one&lt;/strong&gt; and keeps doing this until the Callback queue is also empty.&lt;/p&gt;

&lt;p&gt;As soon the Callstack was empty, the event loop looked in the Callback queue for any pending callback function. But will not find one. Probably you know the reason. The rest of our program will a be executed in few &lt;strong&gt;milliseconds&lt;/strong&gt; but the browser sends our callback function(task) to callback queue after a specified time. &lt;br&gt;
So what next? Did our program fail here? Of course not. As clear from the name, the event loop is a loop and keeps checking again and again.&lt;/p&gt;

&lt;p&gt;After &lt;strong&gt;1000ms&lt;/strong&gt; our callback(task) is sent to the callback queue by the browser. At this point in time, the Callstack is already empty, and immediately event loop transfers our task to the Callstack, where it gets executed similar to any other program.&lt;/p&gt;

&lt;p&gt;Hopefully, most of the concepts will be clear in your mind by now. If you still have some confusion, let's take a couple of more examples.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--QckTm2lQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eq61es6tbyrly8lzx0yc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--QckTm2lQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eq61es6tbyrly8lzx0yc.png" alt="Callback queue demonstration with setTimeout" width="663" height="397"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This program is exactly the same as the previous one with only one change, Delay time is set to 0 for setTimeout. Can you guess what would be the output of this code?&lt;/p&gt;

&lt;p&gt;Well if you guessed &lt;strong&gt;1 2 3&lt;/strong&gt;, this is not the correct answer. Let me explain how?&lt;/p&gt;

&lt;p&gt;The first statement &lt;code&gt;console.log(1)&lt;/code&gt; will be executed exactly as we have already discussed.&lt;/p&gt;

&lt;p&gt;The twist comes in the second statement, setTimeout. We have set a &lt;strong&gt;0ms&lt;/strong&gt; delay time, and we expect it to run &lt;strong&gt;immediately&lt;/strong&gt;. And then 3rd statement should be executed. But this is not the case here.&lt;/p&gt;

&lt;p&gt;When setTimeout is encountered and added to Callstack, and being a web API, it adds a task to the browser and fades out of execution context. As we haven't added any delay, &lt;strong&gt;immediately&lt;/strong&gt; the browser sends our task to the callback queue. &lt;/p&gt;

&lt;p&gt;At the very moment, the JavaScript engine is executing the 3rd statement of our program &lt;code&gt;console.log(3)&lt;/code&gt;. As Callbacks are only transported to the main Callstack after it is empty. Our callback has to sit and wait inside the Callback queue until our main Callstack is empty. &lt;/p&gt;

&lt;p&gt;As soon FEC of &lt;code&gt;console.log(3)&lt;/code&gt; finishes execution, the Callstack is empty, The event loop comes into play, checks the Callback queue for any pending scheduled tasks, and guess what finds one. The eventloop transfers our callback to the Callstack and it gets executed.&lt;/p&gt;

&lt;p&gt;So this way output is &lt;strong&gt;1 3 2&lt;/strong&gt; not &lt;strong&gt;1 2 3&lt;/strong&gt;. Reason is the fact that the eventloop only transfers callbacks from the Callback queue to Callstack after it is empty.&lt;/p&gt;

&lt;h3&gt;
  
  
  Challenge for you
&lt;/h3&gt;

&lt;p&gt;I hope your concepts regarding Callback queue, Web APIs, and eventloop are clear now. So I have a little to do for you. Consider this code and predict the output. Sounds good?&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--33AzDOTd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t162waz55yuwpgqeu1i3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--33AzDOTd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t162waz55yuwpgqeu1i3.png" alt="Callback queue demontration with setTimeout" width="663" height="579"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Take your time, make notes let me know your first assessment in the comment section.&lt;/p&gt;

&lt;p&gt;Let's do it together as well.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step1
&lt;/h4&gt;

&lt;p&gt;&lt;code&gt;console.log(1)&lt;/code&gt; is added to the main Calllstack and executed. Pops out of the execution stack.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step2
&lt;/h4&gt;

&lt;p&gt;setTimeout no 1 is added to the Callstack, it adds a task to the browser and pops out of the stack.&lt;/p&gt;

&lt;p&gt;At this stage, the browser container has 1 task(setTimeout 1), with a timer of &lt;strong&gt;1000ms&lt;/strong&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step3
&lt;/h4&gt;

&lt;p&gt;setTimeout no 2 is added to the Callstack next, and adds a task to the browser and pops out of the stack.&lt;/p&gt;

&lt;p&gt;At this stage, the browser container has 2 tasks, task1(setTimeout1) and task2(setTimeout2) with a timer of &lt;strong&gt;1000ms&lt;/strong&gt; and &lt;strong&gt;0ms&lt;/strong&gt; respectively.&lt;/p&gt;

&lt;p&gt;Here is the twist. We know that task2 was added after task1, but task2 has no delay at all 0ms. So task2 will be sent to the callback queue before the task1.&lt;/p&gt;

&lt;p&gt;Let's update our state, at this point we have only 1 task left in the browser container(task1), and we have one callback function(task2) in the callback queue. So far only 1 statement was executed &lt;code&gt;console.log(1)&lt;/code&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step4
&lt;/h4&gt;

&lt;p&gt;Then comes the 3rd setTimeout API. It is added to the Callstack, it adds a task to the browser. This task3 has a 500ms delay. This means it will be sent to the Callback queue after half a second.&lt;/p&gt;

&lt;p&gt;So far, we have 1 callback function(task2) sitting in the Callback queue, and 2 tasks, task1, and task3 waiting in the browser container with a delay of &lt;strong&gt;1000ms&lt;/strong&gt; and &lt;strong&gt;500ms&lt;/strong&gt; respectively.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step5
&lt;/h4&gt;

&lt;p&gt;Statement 5 in the main script is executed immediately and popped out of the Callstack.&lt;/p&gt;

&lt;p&gt;Now we have executed 2 statements, 2 tasks are waiting in the browser container, and 1 task sitting in the callback queue.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step6
&lt;/h4&gt;

&lt;p&gt;Here comes out 4th and final setTimeout. It has a delay set to &lt;strong&gt;250ms&lt;/strong&gt;. It is added to the Callstack and pops out after adding another task to the browser. At this point in time, we have 3 tasks in the browser container;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Task1&lt;/strong&gt;: Added by setTimeout1 with a timer of &lt;strong&gt;1000ms&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Task3&lt;/strong&gt;: Added by setTimeout1 with a timer of &lt;strong&gt;500ms&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Task4&lt;/strong&gt;: Added by setTimeout1 with a timer of &lt;strong&gt;250ms&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As we know the task is sent to the callback queue after the time specified. So task 4 will go first, followed by task3, and task 1 will be added to the callback queue at the last.&lt;/p&gt;

&lt;h3&gt;
  
  
  State of Callback queue
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--aHV4psfp--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ya8xdtyz3rd0neub5ov.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--aHV4psfp--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ya8xdtyz3rd0neub5ov.png" alt="Callback queue container" width="495" height="557"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As our Callstack is empty at this point, the Eventloop will start transferring callbacks to Callstack 1 by 1. This will happen first in, first out manner. Mean the oldest callback function will be sent to Callstack first. &lt;/p&gt;

&lt;p&gt;So, first of all, task 2 will be transferred to the Callstack. It will be executed by logging &lt;code&gt;3&lt;/code&gt; to the console.&lt;/p&gt;

&lt;p&gt;Then, task 4 is transferred resulting in the logging of &lt;code&gt;6&lt;/code&gt; to the console.&lt;/p&gt;

&lt;p&gt;Then task 3 and at last task 1 logging &lt;code&gt;4&lt;/code&gt; and &lt;code&gt;2&lt;/code&gt; to the console respectively.&lt;/p&gt;

&lt;p&gt;So do we get, &lt;strong&gt;1 5 3 6 4 2&lt;/strong&gt;. This is the magic key. Hopefully, you got the same.&lt;/p&gt;

&lt;h4&gt;
  
  
  Credits and Motivations
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Elegant guide on &lt;a href="https://medium.com/@gemma.croad/understanding-the-javascript-runtime-environment-4dd8f52f6fca#:~:text=What%20is%20the%20runtime%20environment,and%20make%20the%20code%20work."&gt;JavaScript Runtime Environment&lt;/a&gt; by &lt;a href="https://medium.com/@gemma.croad"&gt;Gemma Croad&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Wrapping Up&lt;br&gt;
So this was part 2 of &lt;a href="https://medium.com/@idrazhar/0-to-1-series-how-javascript-works-under-the-hood-ffca74f1cc65"&gt;JavaScript under the hood&lt;/a&gt;. Hopefully, you got some value from this guide, and if you did please let me know in the comment section. This will give me another level of motivation, so I keep writing articles like this.&lt;/p&gt;

&lt;p&gt;Till then, Stay safe, and try to keep others safe.&lt;/p&gt;

&lt;p&gt;See you soon💓&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>executioncontext</category>
      <category>scope</category>
      <category>webdev</category>
    </item>
    <item>
      <title>0 to 1- How JavaScript works under the hood</title>
      <dc:creator>Azhar Dev</dc:creator>
      <pubDate>Mon, 18 Jul 2022 14:18:00 +0000</pubDate>
      <link>https://dev.to/idrazhar/0-to-1-series-how-javascript-works-under-the-hood-157f</link>
      <guid>https://dev.to/idrazhar/0-to-1-series-how-javascript-works-under-the-hood-157f</guid>
      <description>&lt;p&gt;Many developers have been coding in JavaScript to carry out its legacy since &lt;a href="https://en.wikipedia.org/wiki/Brendan_Eich" rel="noopener noreferrer"&gt;&lt;strong&gt;Brendan Eich&lt;/strong&gt;&lt;/a&gt; developed JavaScript back in &lt;strong&gt;1995&lt;/strong&gt;. If someone actually wants to learn JavaScript you need to understand JavaScript. You need to know the history of JavaScript, what problem it actually solves, and how JavaScript works behind the scene. This background info will help you out when you will be coding and when you are learning some new features.&lt;/p&gt;

&lt;p&gt;In this article we will learn little &lt;strong&gt;history&lt;/strong&gt; of JavaScript, how JavaScript works behind the scenes? What is the &lt;strong&gt;Runtime environment&lt;/strong&gt;? What role does the &lt;strong&gt;JavaScript engine&lt;/strong&gt; play in code execution? What the heck is &lt;strong&gt;Execution context&lt;/strong&gt;? What is Scope, &lt;strong&gt;TDZ&lt;/strong&gt;, and a lot more?&lt;/p&gt;

&lt;p&gt;You ready 😉&lt;/p&gt;

&lt;h2&gt;
  
  
  JavaScript History
&lt;/h2&gt;

&lt;p&gt;First of let's discuss the need for JavaScript, so you can have some idea of why are you using JS and what was its purpose.&lt;/p&gt;

&lt;p&gt;In the early days of the web (yeah, stone Age 😉), there were ways to create web pages(HTML was released in 1993), but there was no effective way to manipulate them. As we can these days with &lt;a href="https://medium.com/r/?url=https%3A%2F%2Fwww.w3.org%2FTR%2FWD-DOM%2Fintroduction.html%23%3A~%3Atext%3DThe%2520Document%2520Object%2520Model%2520%28DOM%2Cdocument%2520is%2520accessed%2520and%2520manipulated." rel="noopener noreferrer"&gt;DOM&lt;/a&gt; (Document Object Model - will be discussed later).  So those static pages were usually non-interactive. This was the major reason some language needed to be developed to give them life. &lt;/p&gt;

&lt;p&gt;Back in &lt;strong&gt;1995&lt;/strong&gt;, &lt;a href="https://en.wikipedia.org/wiki/Brendan_Eich" rel="noopener noreferrer"&gt;Brendan Eich&lt;/a&gt; stepped forward and developed the first version of JavaScript in mere 10 Days, it's not a typo I really meant 10 Days. It was then called &lt;strong&gt;LiveScript&lt;/strong&gt;(cool name, but I like JavaScript more 😉). At that time JavaScript was like alien technology and was adopted quickly. The community kept expanding, it got better and better, and of course, JavaScript we use is a monster compared to those days.&lt;/p&gt;

&lt;p&gt;At first, It was developed for &lt;strong&gt;Netscape 2&lt;/strong&gt; and became the ECMA-262 standard in 1997. In &lt;strong&gt;1997&lt;/strong&gt;, ECMAScript 1 was released and was supported in Internet Explorer 4 for the first time. Then in 1998, ECMAScript 2 came out, and ECMAScript 3 in 1999. This fourth edition of the language was a bit delayed and was released in 2008 but could not make it to market. The fifth major edition, &lt;strong&gt;ECMAScript 5&lt;/strong&gt; was released in 2009. This version was used for a while and the latest version &lt;strong&gt;ECMAScript 6&lt;/strong&gt; was released back in &lt;strong&gt;2015&lt;/strong&gt;, which is now widely supported in all major browsers with and exception the of Internet Explorer. &lt;a href="https://www.w3schools.com/js/js_history.asp" rel="noopener noreferrer"&gt;Here&lt;/a&gt; you can learn more about the history of your favorite language.&lt;/p&gt;

&lt;p&gt;Here ECMAscript is&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;ECMAScript is a JavaScript standard meant to ensure the interoperability of web pages across different web browsers. It is standardized by Ecma International according to the document ECMA-262. Bascially it standardizes what JavaScript code dos what, so JavaScript behaves the same way in every Browser.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;You cannot possibly learn the language if you do not know how that Language works under the hood. Let's first understand a few important concepts we will be using a lot in this article.&lt;/p&gt;

&lt;h2&gt;
  
  
  JavaScript in plain English
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;JavaScript is an &lt;strong&gt;interpreted language&lt;/strong&gt;, which means, like Java(no similarity with JavaScript except name ), it does not require us to compile it before sending it to Browser to be executed, the interpreter can take raw JS source code and execute it for us.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;JavaScript is &lt;strong&gt;single-threaded&lt;/strong&gt; and &lt;strong&gt;synchronous&lt;/strong&gt; in nature. This means it creates and executes all the tasks with a single execution thread. Tasks are &lt;strong&gt;queued&lt;/strong&gt; one after another and the next task needs to sit and wait until the active task is completed.  There are still ways to run JS code &lt;strong&gt;asynchronously&lt;/strong&gt;, which we will discuss further in this article.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;JavaScript is &lt;strong&gt;non-blocking&lt;/strong&gt; programming or scripting language which does not block upcoming tasks if a program is taking so long, with the help of &lt;strong&gt;Web APIs&lt;/strong&gt;, Callback queue, and event loop. For now, you might find this non-blocking statement contradictory to the above single-threaded statement. But we will discuss all these concepts in great detail in a while. You just need to be with me for the next few minutes.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;JavaScript is a &lt;strong&gt;dynamically-typed&lt;/strong&gt; language, which means &lt;code&gt;var&lt;/code&gt; can store any data type, like int, string, or object, unlike other statically typed languages like C, and C++ in which we have to explicitly specify variable type &lt;code&gt;datatype variable_name&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  The Runtime Environment
&lt;/h2&gt;

&lt;p&gt;The Runtime Environment is a special environment that provides our code access to built-in libraries, APIs, and objects to our program so it can interact with the outside world and get executed to full fill its noble purpose.&lt;/p&gt;

&lt;p&gt;Runtime Environment is basically a factory where raw JavaScript code gets loaded and with a mixture of &lt;strong&gt;Web APIs&lt;/strong&gt;, &lt;strong&gt;libraries&lt;/strong&gt;, and &lt;strong&gt;objects&lt;/strong&gt; it gets executed. Hopefully, this gives you some sense of the runtime environment. If you still have some doubts, do not worry we will be discussing components of the runtime environment and their part in JS execution in a short while. You just need to hang tight with me, and you will have a very clear picture of JS at the end of this guide.&lt;/p&gt;

&lt;p&gt;In the context of a web &lt;strong&gt;browser&lt;/strong&gt;, the runtime environment consists of following components:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;JavaScript Engine

&lt;ul&gt;
&lt;li&gt; The Callstack or Execution Stack&lt;/li&gt;
&lt;li&gt; The Heap&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;Web Apis (like fetch, setTimeout, DOM, File API)&lt;/li&gt;

&lt;li&gt;The Callback queue&lt;/li&gt;

&lt;li&gt;The Event Loop&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;Runtime environment depends on the context, in which you are running JavaScript code. The runtime environment might look a bit different depending upon the context. For instance in NodeJs environment JavaScript code has no access to Web APIs because they are a feature of web browsers. Basic features will be the same or similar though in case of any context.&lt;/p&gt;

&lt;p&gt;A modern browser is a very complicated piece of software with tens of millions of line lines of code. So it is split into many modules which handle different logic. &lt;/p&gt;

&lt;p&gt;Two of the most important parts of a web browser are the JavaScript engine and a rendering engine.&lt;/p&gt;

&lt;h3&gt;
  
  
  Rendering Engine
&lt;/h3&gt;

&lt;p&gt;The rendering engine paints content on the screen. &lt;a href="https://www.chromium.org/blink/" rel="noopener noreferrer"&gt;Blink&lt;/a&gt; is a rendering engine that is responsible for the entire rendering pipeline including &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction#:~:text=The%20Document%20Object%20Model%20(DOM)%20is%20a%20programming%20interface%20for,can%20interact%20with%20the%20page." rel="noopener noreferrer"&gt;DOM&lt;/a&gt; trees, styles, events, and V8 integration. It parses the DOM trees, resolves styles, and determines the visual geometry of elements on the screen.&lt;/p&gt;

&lt;h3&gt;
  
  
  JavaScript Engine
&lt;/h3&gt;

&lt;p&gt;The purpose of the JavaScript engine is to &lt;strong&gt;translate&lt;/strong&gt; source code that developers write into &lt;strong&gt;machine code&lt;/strong&gt; (binary) that processor can understand. So this is the place or factory you can say, where raw JavaScript gets downloaded, parsed, and transpiled into Machine code that can be understood by Processor.&lt;/p&gt;

&lt;p&gt;JavaScript engine compiles and executes raw JavaScript source code into native machine code. So JavaScript engine is the place where JS source code is downloaded, parsed, interpreted, and executed at the end in form of Binary code. Every major Brower vendor has developed its own JavaScript engine, which basically works the same way. Like Chrome has &lt;a href="https://en.wikipedia.org/wiki/V8_engine" rel="noopener noreferrer"&gt;V8&lt;/a&gt;, Safari has &lt;a href="https://trac.webkit.org/wiki/JavaScriptCore#:~:text=JavaScriptCore%20is%20the%20built%2Din,SquirrelFish%20and%20%E2%80%8BSquirrelFish%20Extreme." rel="noopener noreferrer"&gt;JavaScriptCore&lt;/a&gt;, and Firefox uses &lt;a href="https://spidermonkey.dev/" rel="noopener noreferrer"&gt;SpiderMonkey&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;We will be focusing on the V8 engine in this article. Read what is V8 Engine from Google's words;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;V8 is Google's open-source high-performance JavaScript and WebAssembly engine, written in C++. It is used in Chrome and in &lt;a href="https://nodejs.org/" rel="noopener noreferrer"&gt;Node.js&lt;/a&gt;, among others. It implements ECMAScript and WebAssembly, and runs on Windows 7 or later, macOS 10.12+, and Linux systems that use x64, IA-32, ARM, or MIPS processors. V8 can run standalone or can be embedded into any C++ application.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4&gt;
  
  
  Working of JavaScript Engine(V8)
&lt;/h4&gt;

&lt;p&gt;The first version of V8 was released and used by the Google Chrome team in 2010 when they had some problems displaying Google Maps. Later on, they improved it over time and released another version of V8 in 2017, which is being used by Chrome browser these days.&lt;/p&gt;

&lt;p&gt;The current version was built on this model;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftg929o4d2azb79jwtg52.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftg929o4d2azb79jwtg52.png" alt="V8 JavaScript engine model"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;[Image copied from &lt;a href="https://medium.com/jspoint/how-javascript-works-in-browser-and-node-ab7d0d09ac2f" rel="noopener noreferrer"&gt;this&lt;/a&gt; awesome article by &lt;a href="https://thatisuday.medium.com/" rel="noopener noreferrer"&gt;Uday Hiwarale&lt;/a&gt;]&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Let's break it down;&lt;/p&gt;

&lt;p&gt;V8 engine downloads JS source code and passes it to &lt;strong&gt;Baseline Compiler&lt;/strong&gt; which process and compiles code to lightweight &lt;a href="https://www.mirkosertic.de/blog/2017/06/compiling-bytecode-to-javascript/" rel="noopener noreferrer"&gt;ByteCode&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This bytecode gets passed to an &lt;strong&gt;interpreter&lt;/strong&gt; which is basically an &lt;strong&gt;IntelliSense algorithm&lt;/strong&gt; that knows what JS code dos what. It interprets the bytecode to CPU understandable &lt;a href="https://en.wikipedia.org/wiki/Binary_code" rel="noopener noreferrer"&gt;binary code&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;At the very same time, Bytecode gets passed to the &lt;strong&gt;Optimization compiler&lt;/strong&gt; which optimizes this ByteCode in the background while the application is running. It produces a very &lt;strong&gt;optimized binary code&lt;/strong&gt;, which is eventually replaced with the code in the application, thus giving massive performance and boost.&lt;/p&gt;

&lt;p&gt;This is the final model of the V8 engine. But this was not always like this. After many updates and remodeling, this very optimized version of the engine came into existence.&lt;/p&gt;

&lt;p&gt;This is the basic functioning model of Chrome JavaScript Engine(V8). Other browser vendors use different JavaScript engines. But they function pretty much a similar way.&lt;/p&gt;

&lt;h4&gt;
  
  
  How JavaScript code works in the runtime environment
&lt;/h4&gt;

&lt;p&gt;Unlike other programming languages, JavaScript is single-threaded in runtime, in plain English means it can run only one piece of code at a time. Code runs sequentially, so when one process is taking longer to run, it blocks the rest of the code after that waiting to be executed. Hence sometimes you might see, a Page Unresponsive alert. That usually occurs when some infinite loop of code is encountered in runtime. And it keeps running until all the CPU resources are consumed.&lt;/p&gt;

&lt;p&gt;Consider this eternal loop;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F00huse14tehemooujvnj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F00huse14tehemooujvnj.png" alt="Eternal while loop"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here is what happens when this program is opened in Browser, it uses a single JavaScript execution thread, which is responsible for handling everything on the web page, like scrolling, events handling and fetching data from the server.&lt;/p&gt;

&lt;p&gt;When this kind of infinite loop or huge JavaScript program is encountered, the execution of code gets blocked after it. Because JavaScript is single-threaded in nature and runs one piece at a time. Thus infinite loops keep running again and again until the system is out of resources. And we have to see the "Page Unresponsive" dialog.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4lbbge3rxu9irl06d3jj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4lbbge3rxu9irl06d3jj.png" alt="Page unresponsive dialog"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Thanks to modern browsers they use separate JavaScript execution threads for different tabs, otherwise, our browser would have been frozen if such a heavy program or infinite loop was encountered in one tab on one page. Modern web browsers usually use separate execution threads for different tabs or a single execution thread for one domain (same website on multiple tabs). Chrome uses a one-process-per-site policy so, if multiple domains were open in different tabs, all of them will stop working. Other domains (websites) tabs will keep working fine.&lt;/p&gt;

&lt;p&gt;Let's discuss the JavaScript engine in detail. JavaScript engine consists of mainly two components; The &lt;strong&gt;Callstack&lt;/strong&gt; and the &lt;strong&gt;Heap&lt;/strong&gt;.&lt;/p&gt;

&lt;h5&gt;
  
  
  The Heap
&lt;/h5&gt;

&lt;p&gt;The heap is the unstructured memory storage where variables and objects get stored during program execution. Then the heap, also known as the "memory heap" gets cleaned during garbage collection. I will not talk about it in detail, you can check out this awesome &lt;a href="https://levelup.gitconnected.com/understanding-call-stack-and-heap-memory-in-js-e34bf8d3c3a4" rel="noopener noreferrer"&gt;article&lt;/a&gt;.&lt;/p&gt;

&lt;h5&gt;
  
  
  The Callstack or Execution Stack
&lt;/h5&gt;

&lt;p&gt;We are interested in the call stack, which is basically a LIFO (first in, last out) data storage where current executing contexts are stored while the program is running. We will discuss what &lt;strong&gt;Execution Context&lt;/strong&gt; is in detail in a while. Each entry in the call stack is called a &lt;strong&gt;Stack frame&lt;/strong&gt;. A stack frame contains information about the Execution Context, like its argument object, return address, local variables, etc.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is an Execution context?
&lt;/h3&gt;

&lt;p&gt;JavaScript engine creates a special environment for the execution of JavaScript code, which contains the code that is currently running and everything that aids in its execution. This special environment is called the Execution context.&lt;/p&gt;

&lt;p&gt;During the Execution context runtime, specific code gets parsed by a parser, variables and declarations get stored in memory(&lt;strong&gt;VO&lt;/strong&gt;), and executable bytecode gets generated which is then converted to binary code, which gets executed.&lt;/p&gt;

&lt;p&gt;Two kinds of execution contexts are created during runtime; &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Global Execution Context(GEC)&lt;/li&gt;
&lt;li&gt;Functional Execution Context(FEC)&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Global Execution Context(GEC)
&lt;/h4&gt;

&lt;p&gt;When the JS engine receives some script file, a default Global execution context is created to handle the code at the root of that file, everything which is outside of any function.&lt;/p&gt;

&lt;p&gt;This is the main/default execution context, that encapsulates all of the functional execution contexts.&lt;/p&gt;

&lt;p&gt;There is only one GEC for any script file.&lt;/p&gt;

&lt;h4&gt;
  
  
  Functional Execution Context(FEC)
&lt;/h4&gt;

&lt;p&gt;When the Global execution context encounters a function invocation, a different kind of execution context, very specific to that function gets created which handles all the logic inside that function.&lt;/p&gt;

&lt;p&gt;As there are usually multiple functions inside any script (JavaScript file), every function gets executed in its very own execution context, and there can be multiple Functional Execution Contexts in a single program.&lt;/p&gt;

&lt;h3&gt;
  
  
  How Execution Context is created?
&lt;/h3&gt;

&lt;p&gt;As we already know that execution context has two major tasks, it prepares the script and then executes it. So we will try to understand the execution context in two phases;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Creation Phase&lt;/li&gt;
&lt;li&gt;Execution Phase&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Creation Phase
&lt;/h4&gt;

&lt;p&gt;The creation phase of any execution context completes in three main steps.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Creation of Variable Object&lt;/li&gt;
&lt;li&gt;Creation of the scope chain&lt;/li&gt;
&lt;li&gt;Assignment of &lt;code&gt;this&lt;/code&gt; value&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  Creation Phase: Creation of Variable Object(VO)
&lt;/h5&gt;

&lt;p&gt;For GEC a variable object is created which is basically a memory container, which stores properties for all variables and function declarations and stores references to them. When a variable is encountered in a global execution context property is added to the Variable Object and is initialized(in case defined with &lt;code&gt;var&lt;/code&gt;) with the default value &lt;code&gt;undefined&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;When a function declaration is encountered, a property is added to the Variable Object, and a reference to that function is stored as a value.&lt;/p&gt;

&lt;p&gt;This means before even the start of execution of code, variables and function declarations are available to use. Due to &lt;strong&gt;hoisting&lt;/strong&gt;. We will discuss hoisting in great detail in a while.&lt;/p&gt;

&lt;p&gt;In case of, &lt;strong&gt;FEC&lt;/strong&gt; (functional execution context) doesn't create a VO but an array-like object called the &lt;strong&gt;argument object&lt;/strong&gt;. All the arguments received by a function are stored in this array-like object.&lt;/p&gt;

&lt;h4&gt;
  
  
  Hoisting in JavaScript
&lt;/h4&gt;

&lt;p&gt;JavaScript moves all the variables, function declarations, and class declarations to the top of their scope. This process is called hoisting in JavaScript.&lt;/p&gt;

&lt;p&gt;In plain English, Prior to the execution of code, JavaScript stores all the variables, functions, and class declarations in the memory container, called Variable Object at the top of the scope, this process is known as Hoisting in JavaScript. Basically hoisting is the reason we can access &lt;strong&gt;functions&lt;/strong&gt; and &lt;strong&gt;variables&lt;/strong&gt; even before they are declared.&lt;/p&gt;

&lt;h5&gt;
  
  
  Function hoisting
&lt;/h5&gt;

&lt;p&gt;Some JavaScript developers choose to define all of their functions at the top of the script and later call them at the end. The code below will still work fine due to hoisting, although we are calling the function before it was declared.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3ta3ukhg3mczjs90s992.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3ta3ukhg3mczjs90s992.png" alt="Function hoisting"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h5&gt;
  
  
  Variable Hoisting
&lt;/h5&gt;

&lt;p&gt;Variables declarations are also hoisted. Variables declared with the var keyword are hoisted and initialized with a default value undefined. Mean if you will try to access a variable declared with &lt;code&gt;var&lt;/code&gt;, you will not get an error but the value will be &lt;code&gt;undefined&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If you declare a variable with a &lt;code&gt;let&lt;/code&gt; or &lt;code&gt;const&lt;/code&gt; keyword, their declaration is hoisted but not initialized with a default &lt;code&gt;undefined&lt;/code&gt; value. That's why you will get an &lt;code&gt;uncaught ReferenceError&lt;/code&gt;, when we try to access it before the declaration.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F736m24fazbhkdogsdo2q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F736m24fazbhkdogsdo2q.png" alt="Variable hoisting"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here one thing is really important to discuss. You might be asked in an interview about this.&lt;/p&gt;

&lt;p&gt;Starting from the top of the scope, until the complete initialization of a variable, that variable is said to be in &lt;strong&gt;Temporal Dead Zone(TDZ)&lt;/strong&gt;. You should always try to access variables outside of its TDZ. If you try to access the variable from inside its TDZ, you will get ReferenceError. Here the question arises of where TDZ starts, and where it ends.&lt;/p&gt;

&lt;p&gt;See the code below, you will know Temporal Dead Zone starts at the start of the code block(top of scope) and ends at initialization. Variables declared with &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt; follow the same pattern.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1fhe78v6eudx0obukvfs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1fhe78v6eudx0obukvfs.png" alt="Temporal Dead Zone in case of let and const"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the case of variables declared with &lt;code&gt;var&lt;/code&gt; the scenario is a bit different. And a guilty guy is hoisting. As we already know variables declared &lt;code&gt;var&lt;/code&gt; are hoisted and initialized at the same time with a default value &lt;code&gt;undefined&lt;/code&gt;. And we also know &lt;strong&gt;TDZ&lt;/strong&gt; ends when a variable has been assigned a value. &lt;/p&gt;

&lt;p&gt;This is the reason &lt;code&gt;var&lt;/code&gt; behaves a little differently compared to &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt;. See this &lt;code&gt;code&lt;/code&gt;;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpiz9ejmb2tf0jkp38eph.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpiz9ejmb2tf0jkp38eph.png" alt="Temporal Dead Zone in case of var"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hopefully, TDZ is all clear to you. Let's get back to hoisting.&lt;br&gt;
There is one strict rule of hoisting, that hoisting only works for statements, not expressions. Have a look at this code;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4z627t0l2gav17b4cg5s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4z627t0l2gav17b4cg5s.png" alt="Hoisting rule only statements"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is because we are assigning a function expression to a variable as a value. As we all know variables declared with let keyword are hoisted, but throw &lt;code&gt;ReferenceError&lt;/code&gt; if called within Temporal Dead Zone. This is because their value is not initialized during hoisting and TDZ only ends after the complete initialization of the variable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Quiz Time&lt;/strong&gt;: Here is a small question for you? What would be the output if we used var instead of letting in the above code example. Can you guess whether any error will be thrown or function output will be logged to the console?&lt;/p&gt;

&lt;p&gt;I am sure you guessed it right. The error will be thrown in this case stating something like myFunc is not a function, because at this stage value of the &lt;code&gt;myFunc&lt;/code&gt; variable will be &lt;code&gt;undefined&lt;/code&gt; due to Hoisting. So calling &lt;code&gt;undefined()&lt;/code&gt; will throw an error.&lt;/p&gt;

&lt;h5&gt;
  
  
  Creation Phase: Creation of Scope chain
&lt;/h5&gt;

&lt;p&gt;The scope is a mechanism in JavaScript which determines which piece of code is accessible from where. When a variable, function, or class is declared in a script, it has some address and some boundaries. Beyond those boundaries, it is &lt;strong&gt;inaccessible&lt;/strong&gt;. The scope does answer many questions like from where code can be accessed? and from where it can not be? &lt;/p&gt;

&lt;p&gt;First of all, when the script is loaded in the engine, &lt;strong&gt;global scope&lt;/strong&gt; is created, which basically holds everything which is not inside any function. All the functions and their inner functions can access this global scope.&lt;/p&gt;

&lt;p&gt;When a function is defined in another function, the inner function has access to the code defined in that of the outer function, and that of its parents. This behavior is called &lt;strong&gt;lexical scoping&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Whenever a variable or function is called somewhere, the engine starts looking for an inside the local scope, where it was called. If not found, it looks for parent scopes (Lexical Scoping) one by one, from inner(local) to outermost (global scope). If the variable was not found in local and all the parent scopes including the global root scope, then the engine throws an error.&lt;/p&gt;

&lt;p&gt;Every function execution context creates its scope which determines what variables and functions are accessible where. There are a few cases that we need to discuss to completely understand scoping.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Case 1&lt;/strong&gt;: Variables declared inside a function can be accessed from anywhere inside that function, except for &lt;strong&gt;Temporal Dead Zone&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Case 2&lt;/strong&gt;: Function declared inside a function has access to everything of its parent function and parent's parent function up to the global scope. This is called Lexical Scoping. This concept gave rise to something called &lt;strong&gt;closures&lt;/strong&gt; in JavaScript.&lt;/p&gt;

&lt;p&gt;When a function inside another function is called outside of its context, means outside of the parent function in which it was declared but it still has access to variables of the parent function even after the parent function has finished execution, this associative phenomenon is called &lt;strong&gt;closures&lt;/strong&gt;. This is a very important concept and you definitely should check it out &lt;a href="https://www.freecodecamp.org/news/closures-in-javascript/" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Parent function has no access to anything declared inside of its child functions. The scope is like a one-way mirror, which means you can look outside but now one can look inside.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fltwit2vvff3fkner2qbs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fltwit2vvff3fkner2qbs.png" alt="Scope illustration"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;[Image copied from &lt;a href="https://www.freecodecamp.org/news/execution-context-how-javascript-works-behind-the-scenes/" rel="noopener noreferrer"&gt;this&lt;/a&gt; awesome article by &lt;a href="https://www.freecodecamp.org/news/author/victor-ikechukwu/" rel="noopener noreferrer"&gt;Victor Ikechukwu&lt;/a&gt; at &lt;a href="https://www.freecodecamp.org/" rel="noopener noreferrer"&gt;freeCodeCamp&lt;/a&gt;]&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;As you can see in this image, the function &lt;code&gt;second&lt;/code&gt; has access to all scopes including its own &lt;code&gt;local&lt;/code&gt; scope, the scope of function &lt;code&gt;first&lt;/code&gt;, and the &lt;code&gt;global&lt;/code&gt; scope. But function first has only access to its local scope and the global scope. You can see it has no access to the scope of function &lt;code&gt;second&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The second step of the creation of the Execution context completes here.&lt;/p&gt;

&lt;p&gt;Till now Variable object has been created, scope chain is in place. Let's discuss the third and final step.&lt;/p&gt;

&lt;h5&gt;
  
  
  Creation phase: Setting the value of &lt;code&gt;this&lt;/code&gt;
&lt;/h5&gt;

&lt;p&gt;The next and final step in the creation of execution context is setting the value of &lt;code&gt;this&lt;/code&gt;. this is a special keyword in JavaScript which refers to the scope of the environment where the Execution context belongs.&lt;/p&gt;

&lt;p&gt;Value of &lt;code&gt;this&lt;/code&gt; is different, depending on the context it is being used. Have a look at these cases;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Case 1&lt;/strong&gt;: In Global Execution Context, &lt;code&gt;this&lt;/code&gt; refers to the global window object in the case of browsers. Try logging "this" to the console inside GEC and you will see a &lt;code&gt;window&lt;/code&gt; object. Here is one interesting thing to notice. When you define a variable or function inside GEC, they are saved as a property of the window object. This means these 2 statements are equivalent;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7ubvxrltxjj1o5g3n0xj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7ubvxrltxjj1o5g3n0xj.png" alt="this in GEC comparison"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And this will log true to the console;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4nkl3cc36usojmhe273t.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4nkl3cc36usojmhe273t.png" alt="this in GEC comparison 2"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Case 2&lt;/strong&gt;: Inside FEC, a new &lt;code&gt;this&lt;/code&gt; object is not created, but instead, it refers to the context it belongs to. Like, in this case, &lt;code&gt;this&lt;/code&gt; refers to the global window object. As this function is declared in GEC, this would refer to the global &lt;code&gt;window&lt;/code&gt; object.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fydwa1zmdvtz75ewkbi5x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fydwa1zmdvtz75ewkbi5x.png" alt="this in FEC"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Case 3&lt;/strong&gt;: In the case of objects, using &lt;code&gt;this&lt;/code&gt; inside the methods does not refer to the global object, but the object itself. Look at this example;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F661inhtnzcmntwiesc49.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F661inhtnzcmntwiesc49.png" alt="this inside object methods"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Case 4&lt;/strong&gt;: Inside constructor functions, &lt;code&gt;this&lt;/code&gt; refers to the newly created object, when called with &lt;code&gt;new&lt;/code&gt; keyword like this;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fabh60vpsstq4jqmjpn14.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fabh60vpsstq4jqmjpn14.png" alt="this inside constructor functions"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;With this, the creation phase of Execution Context has been completed. Till now, everything has been stored in VO, the scope chain is created and the value of this is in place.&lt;/p&gt;

&lt;h4&gt;
  
  
  Execution phase
&lt;/h4&gt;

&lt;p&gt;Right after the creation of the execution context. JavaScript engine starts the execution of created context. But Variable Object currently contains all the declarations of that specific execution context but their value is undefined. And you already know we cannot work with &lt;code&gt;undefined&lt;/code&gt;. So JavaScript engine again looks through VO once again and feeds their original values. After this code gets parsed by the parser engine, gets transpiled into lightweight bytecode, which is then converted to binary code(01), which then gets executed.&lt;/p&gt;

&lt;h5&gt;
  
  
  JavaScript Callstack(in terms of execution context)
&lt;/h5&gt;

&lt;p&gt;First of all, the script is loaded in the browser, JavaScript engine creates the Global Execution Context. This GEC is responsible for handling all the code that is not inside of any function.&lt;/p&gt;

&lt;p&gt;Initially, this GEC is the active execution context. When some function is encountered in this GEC, and new Functional Execution Context is created for the execution of that function. That FEC holds all the information about the execution of that function and everything that aids in its execution. This newly created execution context is placed right above the GEC. This process is repeated for every function call and FEC is added and piled up in the so-called &lt;strong&gt;Callstack&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Execution context on the top is executed first, and once that context is executed (something returned), it is popped out of the stack. The very next context becomes an active one and its execution starts. This process is repeated until there is the last GEC left in the stack. It is executed at the end and the script is said to be executed at this point.&lt;/p&gt;

&lt;h5&gt;
  
  
  Conclusion
&lt;/h5&gt;

&lt;p&gt;et's sum up all of this by an example. We try to recall everything we have learned so far in this article.&lt;/p&gt;

&lt;p&gt;Consider this program inside the script file;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbcs7bjvee5t2lqy3hhvo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbcs7bjvee5t2lqy3hhvo.png" alt="Execution stack conclusion img 1"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;First of all this &lt;code&gt;.js&lt;/code&gt; file gets loaded in the browser, and passed to the JavaScript engine for execution. The engine creates a Global Execution Context for this file which handles the execution of the root of this script file, everything that is not inside a function. This GEC is placed at the bottom(or top) of the &lt;code&gt;Execution Stack&lt;/code&gt;. Global Execution Context is created during two phases; the creation phase, and the execution phase.&lt;/p&gt;

&lt;p&gt;Variable &lt;code&gt;name="Victor"&lt;/code&gt; is stored in the Variable Object (&lt;strong&gt;VO&lt;/strong&gt;) of GEC and initialized with the default value &lt;code&gt;undefined&lt;/code&gt; (&lt;strong&gt;hoisting&lt;/strong&gt;).&lt;/p&gt;

&lt;p&gt;Then for all these functions &lt;code&gt;first&lt;/code&gt;, &lt;code&gt;second&lt;/code&gt; and &lt;code&gt;third&lt;/code&gt;, a property is added to VO of GEC, and reference to these functions is stored as value. Hoisting you know 😉.&lt;br&gt;
 &lt;br&gt;
After setting the VO of GEC, the &lt;strong&gt;scope chain&lt;/strong&gt; is created, and value is &lt;code&gt;this&lt;/code&gt; set (&lt;code&gt;window&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;Now starts execution. But the value of &lt;code&gt;name&lt;/code&gt; variable is still &lt;code&gt;undefined&lt;/code&gt; in the VO. And we cannot work with undefined, Right? So once again JS engine looks through VO and feeds the original value of &lt;code&gt;name&lt;/code&gt; variable, which is &lt;code&gt;Victor&lt;/code&gt;. Now we are good to proceed further in our program.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6zvwvj7j5r79leqqyo3u.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6zvwvj7j5r79leqqyo3u.png" alt="Execution Stack Visual"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;First of all, the function &lt;code&gt;first&lt;/code&gt; gets invoked. JS engine creates a Functional Execution Context to handle its execution. This FEC is placed on top of the Global Execution Context, forming a &lt;strong&gt;Callstack&lt;/strong&gt; or &lt;strong&gt;Execution Stack&lt;/strong&gt;. For the period of time, this FEC is the active one, as we already know Execution Context on the top in Callstack is active. Variable &lt;code&gt;a = "Hi!"&lt;/code&gt; gets stored in the FEC, not GEC.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe0o90uy1zywedujfux5s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe0o90uy1zywedujfux5s.png" alt="Execution Stack Visual phase 2"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the next statement, function &lt;code&gt;first&lt;/code&gt; invokes function &lt;code&gt;second&lt;/code&gt;. Another FEC is created and placed on top of the FEC of function &lt;code&gt;first&lt;/code&gt;. Now this FEC is active. Variable &lt;code&gt;b="Hey!"&lt;/code&gt; gets stored in the FEC.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fay7nsidf5s1zb2x8nupf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fay7nsidf5s1zb2x8nupf.png" alt="Execution Stack Visual phase 3"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Then function &lt;code&gt;second&lt;/code&gt; invokes function &lt;code&gt;third&lt;/code&gt;, similarly, FEC is created, and placed on the top of the Execution stack. Variable &lt;code&gt;c = "Hello!"&lt;/code&gt; gets stored in the FEC.&lt;/p&gt;

&lt;p&gt;So far Execution Stack looks like this;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8861al5afhyy7btwudhc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8861al5afhyy7btwudhc.png" alt="Execution Stack Visual phase 4"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And logs &lt;code&gt;Hello Victor&lt;/code&gt; to the console. But wait! Where does Victor come from? Variable &lt;code&gt;name&lt;/code&gt; is not defined in the function &lt;code&gt;third&lt;/code&gt;. You guessed it right, &lt;strong&gt;Scope Chain&lt;/strong&gt;. The function &lt;code&gt;third&lt;/code&gt; looks for name variable inside its local scope, but did not find it. Because of something called &lt;strong&gt;Lexical Scoping&lt;/strong&gt;, it also has access to its parent scope, the Global scope. JavaScript engine looks for &lt;code&gt;name&lt;/code&gt; in global scope and finds it.&lt;/p&gt;

&lt;p&gt;When function &lt;code&gt;third&lt;/code&gt; has completed all of its purposes, its FEC gets popped out of the Execution stack(Callstack).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fay7nsidf5s1zb2x8nupf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fay7nsidf5s1zb2x8nupf.png" alt="Execution Stack Visual phase 5"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Then the very first FEC below it becomes active context and starts execution. Logs &lt;code&gt;Hey! Victor&lt;/code&gt; to the console' and pops out of the Execution stack. Now the last FEC of this program becomes active, logs &lt;code&gt;Hi! Victor&lt;/code&gt; to the console. After execution of all of the statements, it is destroyed and pops out of the Callstack.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6zvwvj7j5r79leqqyo3u.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6zvwvj7j5r79leqqyo3u.png" alt="Execution Stack Visual phase 8"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We are again left with only GEC in the Execution stack. As well it has nothing left to execute it also pops out of the stack.&lt;/p&gt;

&lt;p&gt;Hopefully, this example cleared up most of your doubts. We have discussed the first component of the JavaScript Runtime Environment so far. Hopefully, you find it helpful.&lt;/p&gt;

&lt;h4&gt;
  
  
  So far we have learned
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;A little history of JavaScript&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;JavaScript Runtime&lt;/strong&gt;, which is basically a special environment provided by the browser or context we run our code in. This environment provides us with objects, APIs, and other components so our code can interact with the outside world and get executed.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Components of runtime environment&lt;/strong&gt;; like JavaScript engine, Web APIs, Callback queue, and Eventloop.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;JavaScript engine&lt;/strong&gt;, which again consists of Callstack or Execution Stack and the Heap.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Execution Context&lt;/strong&gt;, which is basically a special environment for the execution of JavaScript code, contains the code that is currently running and everything that aids in its execution. This special environment is called the Execution context. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Types of execution context&lt;/strong&gt;; like Global Execution Context(&lt;strong&gt;GEC&lt;/strong&gt;) and Functional Execution Context(&lt;strong&gt;FEC&lt;/strong&gt;).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;The creation phase of Execution Context&lt;/strong&gt;, which completes in three phases; Creation of VO, Scope chain building, and the setting value of this.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;The execution phase of Execution Context&lt;/strong&gt;, we learned how GEC is created once the script is loaded and how every function creates its own FEC. They keep stacking on one another unless they return something and get popped out of Stack.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Scoping and Temporal Dead Zone&lt;/strong&gt;, we learned how functions can access declarations from their parent scope via &lt;strong&gt;Lexical Scoping&lt;/strong&gt;. We briefly discussed TDZ as well.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  The drawback of JS &lt;strong&gt;single-threaded&lt;/strong&gt; nature
&lt;/h4&gt;

&lt;p&gt;As we all know JavaScript is single-threaded in nature, as it has only one heap and one stack. The next program has to sit and wait until the current program finishes execution, heap, and Callstack get cleared and the new program starts executing.&lt;/p&gt;

&lt;p&gt;But what if, the currently executing task is taking so long, what if our current execution context is requesting some data from the server(slow server), definitely it would take some time. In this case, the Callstack queue will be &lt;strong&gt;stuck&lt;/strong&gt; as JavaScript only executes one task at a time. All the execution contexts that are next to be executed will keep waiting until our current guilty Execution context is resolved. How we can handle this sort of behavior. How can we schedule some tasks, or park some expensive tasks so that we can keep our application going? How can we make our &lt;strong&gt;synchronous&lt;/strong&gt; JavaScript &lt;strong&gt;asynchronous&lt;/strong&gt;? &lt;/p&gt;

&lt;p&gt;This is where &lt;strong&gt;Web APIs&lt;/strong&gt;, &lt;strong&gt;Callback queue&lt;/strong&gt;, and &lt;strong&gt;Eventloop&lt;/strong&gt; come to the rescue. My plan was to discuss all of these concepts in a single guide, but the length grew more than I expected.&lt;/p&gt;

&lt;h4&gt;
  
  
  What Next?
&lt;/h4&gt;

&lt;p&gt;Now we are left with the other three components of JavaScript Runtime,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Web APIs&lt;/li&gt;
&lt;li&gt;The Callback Queue&lt;/li&gt;
&lt;li&gt;The Eventloop&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I will be dropping another guide like this on these left components. If you want to get notified of the next part, follow me 😉.&lt;/p&gt;

&lt;p&gt;This was the first component of the JavaScript runtime, the Working of the JavaScript engine in the code execution. I have tried to simplify all the concepts so even absolute beginners can understand them. Hopefully, you were able to understand it, and found it helpful.&lt;/p&gt;

&lt;h4&gt;
  
  
  Credits and Motivations
&lt;/h4&gt;

&lt;p&gt;While writing this guide, I found really awesome articles you should also check. These articles helped me write this extensive guide.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Really awesome article &lt;a href="https://medium.com/jspoint/how-javascript-works-in-browser-and-node-ab7d0d09ac2f" rel="noopener noreferrer"&gt;How does JavaScript and JavaScript engine work in the browser and node?&lt;/a&gt; by &lt;a href="https://medium.com/@thatisuday" rel="noopener noreferrer"&gt;Uday Hiwarale&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;An extensive article on &lt;a href="https://www.freecodecamp.org/news/execution-context-how-javascript-works-behind-the-scenes/" rel="noopener noreferrer"&gt;JavaScript Execution Context&lt;/a&gt; by &lt;a href="https://www.freecodecamp.org/news/author/victor-ikechukwu/" rel="noopener noreferrer"&gt;Victor Ikechukwu&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Elegant guide on &lt;a href="https://medium.com/@gemma.croad/understanding-the-javascript-runtime-environment-4dd8f52f6fca#:~:text=What%20is%20the%20runtime%20environment,and%20make%20the%20code%20work." rel="noopener noreferrer"&gt;JavaScript Runtime Environment&lt;/a&gt; by &lt;a href="https://medium.com/@gemma.croad" rel="noopener noreferrer"&gt;Gemma Croad&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Final Words
&lt;/h4&gt;

&lt;p&gt;If you liked this guide and want to get notified of my next articles like this, please do follow me. If your friend is struggling with these concepts, do share this guide.&lt;/p&gt;

&lt;p&gt;Till then, Stay safe, and try to keep others safe.&lt;/p&gt;

&lt;p&gt;See you soon💓&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>executioncontext</category>
      <category>scope</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Implementing Layout Structure in NextJs the right way</title>
      <dc:creator>Azhar Dev</dc:creator>
      <pubDate>Mon, 04 Jul 2022 10:16:38 +0000</pubDate>
      <link>https://dev.to/idrazhar/implementing-layout-structure-in-nextjs-the-right-way-1dcj</link>
      <guid>https://dev.to/idrazhar/implementing-layout-structure-in-nextjs-the-right-way-1dcj</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs9bh0b9hj8b3idmknfkn.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs9bh0b9hj8b3idmknfkn.jpeg" alt="Layout Structure in NextJs"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Intro &amp;amp; Why Layouts?
&lt;/h2&gt;

&lt;p&gt;When I started coding in NextJs, I really struggled while implementing Layout based architecture. The React model allows us to deconstruct a page into a series of components. Many of these components are often reused between pages. For example, you might have the same Header and Footer on every page.&lt;/p&gt;

&lt;p&gt;I read some articles and came to a proper solution for Layout based architecture in simple or complex NextJs applications.&lt;/p&gt;

&lt;h3&gt;
  
  
  Tutorial Outcomes
&lt;/h3&gt;

&lt;p&gt;At the end of the tutorial you will be able to;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Create a global layout for NextJs pages&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Create multiple dedicated layouts for different type of pages like GlobalLayout, DashboardLayout.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;You will learn how to fix remount and &lt;strong&gt;state persistence&lt;/strong&gt; issues while implementing layouts in &lt;strong&gt;NextJs&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Setting up the NextJs project
&lt;/h2&gt;

&lt;p&gt;Let's create a new NextJs project by running CNA(create-next-app) command with the default template, in the terminal(personally prefer Git Bash),&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

npx create-next-app &amp;lt;app-name&amp;gt;
# or
yarn create next-app


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Navigate to project directory,&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

cd &amp;lt;app-name&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Run newly created NextJs app in a development environment,&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

npm run dev
// or
npm start


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now application should be running at &lt;code&gt;localhost:300&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Lets look at the directories you will get after bootstraping NextJs application;&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&lt;p&gt;/&amp;lt;app-name&amp;gt;&lt;br&gt;
   /pages&lt;br&gt;
        /_app.js&lt;br&gt;
        /index.js&lt;br&gt;
   /public&lt;br&gt;
   /styles&lt;/p&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Adding necessory components&lt;br&gt;
&lt;/h2&gt;

&lt;p&gt;Create another file inside the pages directory, named &lt;code&gt;about.js&lt;/code&gt;, which will be mapped to &lt;code&gt;/about&lt;/code&gt; as About page.&lt;/p&gt;

&lt;p&gt;Create another directory inside the root directory as components;&lt;/p&gt;

&lt;p&gt;Inside the Components directory create directories named, &lt;strong&gt;Layout&lt;/strong&gt;, &lt;strong&gt;Header&lt;/strong&gt;, and &lt;strong&gt;Footer&lt;/strong&gt;, each with &lt;code&gt;index.js&lt;/code&gt; file inside it.&lt;/p&gt;

&lt;p&gt;The project directory should look like this;&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&lt;p&gt;/&amp;lt;app-name&amp;gt;&lt;br&gt;
   /pages&lt;br&gt;
      /_app.js&lt;br&gt;
      /index.js&lt;br&gt;
      /about.js&lt;br&gt;
   /public&lt;br&gt;
   /styles&lt;br&gt;
   /components&lt;br&gt;
      /Layout&lt;br&gt;
          /index.js&lt;br&gt;
      /Header&lt;br&gt;
          /index.js&lt;br&gt;
      /Footer&lt;br&gt;
          /index.js&lt;/p&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Adding Content&lt;br&gt;
&lt;/h2&gt;

&lt;p&gt;Now open index.js inside the /pages directory, and clean up the mockup code initially created by running the &lt;code&gt;create-next-app&lt;/code&gt; command. Add the following code instead;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjzdwb58qqeiv8nbfliqg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjzdwb58qqeiv8nbfliqg.png" alt="Homepage content"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And inside the about.js page,&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fffdggje3fag15p84woc5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fffdggje3fag15p84woc5.png" alt="About page content"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Implementing Layout
&lt;/h2&gt;

&lt;p&gt;Now you can see, that Components like the Header, Footer are being shared between both the pages. We are going to separate these shared components inside the Layout component, so we do not need to import them in every single page.&lt;/p&gt;

&lt;p&gt;Open the &lt;code&gt;index.js&lt;/code&gt; file inside &lt;strong&gt;Layout&lt;/strong&gt; directory and add this code;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F97kyc9t8o5x37g0ty9es.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F97kyc9t8o5x37g0ty9es.png" alt="Layout component content"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;What are we doing here exactly? Nothing special. We are using the &lt;code&gt;children&lt;/code&gt;prop provided by reacting, which will let us wrap pages inside Layout. Anything wrapped inside this Layout component will be added to react render tree between &lt;code&gt;&amp;lt;main&amp;gt;&lt;/code&gt; tag at,&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&amp;lt;main&amp;gt;{children}&amp;lt;/main&amp;gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now let's implement this layout inside our pages, and make the following changes to &lt;code&gt;index.js&lt;/code&gt; and &lt;code&gt;about.js&lt;/code&gt; inside pages directory;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2ngz25wxr9bkislmpook.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2ngz25wxr9bkislmpook.png" alt="Homepage with Layout"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;and inside &lt;code&gt;/pages/about.js&lt;/code&gt;,&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4khx65ja0oeyetddt6f3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4khx65ja0oeyetddt6f3.png" alt="About page with Layout"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hurrah!&lt;/strong&gt; We got it. We have successfully implemented Layout architecture inside our NextJs app. But hold on, there is a major drawback to this implementation. Unnecessary &lt;strong&gt;remounting&lt;/strong&gt; and &lt;strong&gt;rerender&lt;/strong&gt; at every navigation 😒. Let me explain.&lt;/p&gt;

&lt;h2&gt;
  
  
  Fixing the Remounting and Rerendering issue
&lt;/h2&gt;

&lt;p&gt;First of all, let me demonstrate what I mean by unnecessary re-renders and remounting issues. Let's start a development server, by running&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm run dev&lt;/code&gt; or &lt;code&gt;npm start&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;If you had followed me along, you must see this basic page when visiting &lt;code&gt;localhost:3000&lt;/code&gt; in browser of your choice(unless its &lt;strong&gt;Internet Explorer&lt;/strong&gt; 😉)&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcfacpz5z45lrdpvo8iiw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcfacpz5z45lrdpvo8iiw.png" alt="Layout implementation output"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Isn't it ugly, right? 😊, I guessed your answer. Let's give it a bit of shape with Tailwind CSS(really awesome, if you haven't tried it, you should give it a shot).&lt;/p&gt;

&lt;p&gt;I have added some styles, and a useEffect hook to demonstrate to you, what is actually going on. Have a look;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4kssl13x7hkk75o9dte4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4kssl13x7hkk75o9dte4.png" alt="Header component useEffect listner"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;&lt;code&gt;useEffect&lt;/code&gt;&lt;/strong&gt;hook was provided in ReactJs after &lt;strong&gt;v16.8&lt;/strong&gt;, which pretty much replaces the 3 life cycle methods (&lt;strong&gt;&lt;code&gt;componentDidMount&lt;/code&gt;&lt;/strong&gt;, &lt;strong&gt;&lt;code&gt;componentWillUpdate&lt;/code&gt;&lt;/strong&gt;, &lt;strong&gt;&lt;code&gt;componentWillUnmout&lt;/code&gt;&lt;/strong&gt;) of react class-based implementation.&lt;br&gt;
Now our Header component should look like this;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbzhjgr0ng8izl8pnkeqh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbzhjgr0ng8izl8pnkeqh.png" alt="Header component content"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Testing Phase 1
&lt;/h4&gt;

&lt;p&gt;Setup is done, now let's test this out. Open a terminal, and refresh your page. You must see in the terminal &lt;code&gt;Header mounted&lt;/code&gt;;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpumuyvyn1gm9hv3u8jhm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpumuyvyn1gm9hv3u8jhm.png" alt="Layout implmentation Output"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now it's time to navigate to the About page, by clicking About in the Header, you will see that header &lt;strong&gt;first unmounts and then re-mounts again.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fraj9n2ii8gx2n9h1rosk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fraj9n2ii8gx2n9h1rosk.png" alt="Layout implementation console output"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Is this okay? You guessed it right. When navigating between pages, we want to &lt;strong&gt;persist page state&lt;/strong&gt; (input values, scroll position, etc.) for a &lt;strong&gt;Single-Page Application (SPA) experience&lt;/strong&gt;. But in our case, this is doing nothing, just separating the shared components, which is good but now what we want to achieve.&lt;/p&gt;

&lt;h3&gt;
  
  
  Okay! Fix time
&lt;/h3&gt;

&lt;p&gt;NextJs comes with the solution itself, by providing us with getLayout method. We need to refactor this code a bit, and we are good to go.&lt;/p&gt;

&lt;p&gt;When using Next.js we often need to override the global App component to get access to some features like &lt;em&gt;persisting state&lt;/em&gt;, or &lt;em&gt;global layouts&lt;/em&gt;. This can be done by creating a file_app.js directly in the &lt;code&gt;/pages/&lt;/code&gt; folder. If this file exists, then Next.js will use this instead of the default App.&lt;/p&gt;

&lt;p&gt;Time to mess with _app.js file;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhuqtrm3vr1ot29jx9b8p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhuqtrm3vr1ot29jx9b8p.png" alt="_app.js content"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;What are we exactly doing here, we are telling NextJs to use Layout as specified at the page level, while preserving the memory(state, scroll position, etc.). When navigating between pages, we want to persist page state (input values, scroll position, etc.) for a Single-Page Application (SPA) experience.&lt;/p&gt;

&lt;p&gt;This layout pattern enables state persistence because the React component tree is maintained between page transitions. With the component tree, React can understand which elements have changed to preserve the state.&lt;/p&gt;

&lt;h3&gt;
  
  
  Refactoring Page Layouts
&lt;/h3&gt;

&lt;p&gt;Let's refactor code inside pages, &lt;code&gt;index.js&lt;/code&gt; and &lt;code&gt;about.js&lt;/code&gt;.&lt;br&gt;
Move the Layout from the component return state to &lt;code&gt;Component.getLayout&lt;/code&gt; method like;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6u5wwpx6bqgsxkuc9fv8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6u5wwpx6bqgsxkuc9fv8.png" alt="Homepage content with Layout"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;and for &lt;code&gt;/about.js&lt;/code&gt; page;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4feoo4nf473lnny7v35u.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4feoo4nf473lnny7v35u.png" alt="About page content with layout"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Testing
&lt;/h3&gt;

&lt;p&gt;Let's test it again. clear console and refresh again. You must see a message Header mounted in the console, now try to navigate to the About page, and Boom 😍.&lt;/p&gt;

&lt;p&gt;You see that no more remounting, state loss. We together have just implemented a proper Layout architecture in NextJs.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;You can easily add multiple layouts inside your NextJs app, like Dashboard Layout, etc. You just need to create a Layout, and add common components, like a Sidebar, Dashboard Header, and Dashboard Footer in case of Dashboard Layout. And the next step would be to wrap pages inside this layout.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Simple isn't it.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Hopefully, you got some value from this article, in case you have any queries please let me know in the comment section.&lt;/p&gt;

&lt;p&gt;Thanks a lot. I am &lt;strong&gt;&lt;a href="https://www.azharzaman.com" rel="noopener noreferrer"&gt;Azhar Zaman&lt;/a&gt;&lt;/strong&gt; and I will see you in another amazing tutorial like this.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Till then be safe and try to keep others safe.&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>nextjs</category>
      <category>layouts</category>
      <category>frontend</category>
      <category>react</category>
    </item>
  </channel>
</rss>
