<?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: Sarthak</title>
    <description>The latest articles on DEV Community by Sarthak (@sarthaksam).</description>
    <link>https://dev.to/sarthaksam</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%2F537614%2F9b8870fb-decf-42b2-95a1-0f179fc880a6.png</url>
      <title>DEV Community: Sarthak</title>
      <link>https://dev.to/sarthaksam</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/sarthaksam"/>
    <language>en</language>
    <item>
      <title>This keyword in Javascript</title>
      <dc:creator>Sarthak</dc:creator>
      <pubDate>Tue, 15 Jun 2021 09:32:50 +0000</pubDate>
      <link>https://dev.to/sarthaksam/this-keyword-in-javascript-3o2p</link>
      <guid>https://dev.to/sarthaksam/this-keyword-in-javascript-3o2p</guid>
      <description>&lt;p&gt;The &lt;strong&gt;this&lt;/strong&gt; keyword in javascript behaves a bit differently than other languages. That is why it confuses a lot of people. If you are one of them, then this post is a great start for you to know about it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;So what is this and what is its value?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is a property of an execution context (global, function, or eval) that, in non–strict mode, is always a reference to an object and in strict mode can be any value.&lt;/p&gt;

&lt;p&gt;In most cases, the value of this is determined by how a function is called(runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--i-OtLhyG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9qios6weoqgy8dsmhlym.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--i-OtLhyG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9qios6weoqgy8dsmhlym.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let’s now see what is the value of this in different contexts - &lt;/p&gt;

&lt;h3&gt;
  
  
  Global Context
&lt;/h3&gt;

&lt;p&gt;In the global execution context (outside of any function), &lt;strong&gt;this&lt;/strong&gt; refers to the global object whether in strict mode or not.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--03Bdwl0y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kqkgwtycsq5k1lnw10s4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--03Bdwl0y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kqkgwtycsq5k1lnw10s4.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Function Context
&lt;/h3&gt;

&lt;p&gt;For Functions, the value of &lt;strong&gt;this&lt;/strong&gt; is determined by how they are called.&lt;/p&gt;

&lt;p&gt;For functions called directly without setting the value of this, &lt;strong&gt;this&lt;/strong&gt; defaults to the global object, which in the browser is the window object.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--XmimX7_o--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tbyogf2pg561mt5vejkw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--XmimX7_o--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tbyogf2pg561mt5vejkw.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;However, in strict mode, the value of &lt;strong&gt;this&lt;/strong&gt; is set to undefined if it is not set while entering an execution context.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ds4seSZx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aw4i2vmn39zswphokcm3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ds4seSZx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aw4i2vmn39zswphokcm3.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Calling a function with a particular value of this
&lt;/h3&gt;

&lt;p&gt;We can call a function with a specific &lt;strong&gt;this&lt;/strong&gt; value using the call and apply method.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Call()&lt;/strong&gt;&lt;br&gt;
The call() method calls a function with a given &lt;strong&gt;this&lt;/strong&gt; value and arguments provided individually.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--tHb2-x74--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cxguibbz3hqkkhrdx34o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--tHb2-x74--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cxguibbz3hqkkhrdx34o.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Apply()&lt;/strong&gt;&lt;br&gt;
The call() method calls a function with a given &lt;strong&gt;this&lt;/strong&gt; value and arguments provided as an array.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--E6HUuH-e--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c7cvhuwlz4g3f2wmelm3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--E6HUuH-e--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c7cvhuwlz4g3f2wmelm3.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bind()&lt;/strong&gt;&lt;br&gt;
The bind method creates a new function with the same body and scope as the function on which it is called, but &lt;strong&gt;this&lt;/strong&gt; of the new function is permanently bound to the first argument of the bind method.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--NQrX8fis--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nek5gjsinoa1ldgpzr38.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--NQrX8fis--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nek5gjsinoa1ldgpzr38.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Arrow Functions
&lt;/h3&gt;

&lt;p&gt;In arrow functions, the value of &lt;strong&gt;this&lt;/strong&gt; is equal to the enclosing lexical context’s &lt;strong&gt;this&lt;/strong&gt; value. So, In global code, it will be set to the global object.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--bc_FM9_---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mssxrqxiqlhaxa7pv7db.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bc_FM9_---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mssxrqxiqlhaxa7pv7db.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Ph5Pgues--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/56itksqj2y7qz9y8xdxo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Ph5Pgues--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/56itksqj2y7qz9y8xdxo.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; We cannot set this value of arrow functions even using call, apply and bind methods.&lt;/p&gt;

&lt;h3&gt;
  
  
  As an object method
&lt;/h3&gt;

&lt;p&gt;When a function is called as a method of an object, its &lt;strong&gt;this&lt;/strong&gt; is set to the object the method is called on.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Gk765WLu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s43qaujsxrda7jc11ayb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Gk765WLu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s43qaujsxrda7jc11ayb.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I hope this post gives you a fair amount of idea about how &lt;strong&gt;this&lt;/strong&gt; works in JavaScript.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>Macrotasks and Microtasks in JavaScript</title>
      <dc:creator>Sarthak</dc:creator>
      <pubDate>Mon, 14 Jun 2021 09:47:56 +0000</pubDate>
      <link>https://dev.to/sarthaksam/macrotasks-and-microtasks-in-javascript-3kng</link>
      <guid>https://dev.to/sarthaksam/macrotasks-and-microtasks-in-javascript-3kng</guid>
      <description>&lt;p&gt;Do you get confused between why promises are executed first rather than setTimeout or setInterval? Or you messed up an interview because of this. Let's find out why this happens&lt;/p&gt;

&lt;p&gt;First check your understanding of microtask and macrotask using an output question. So, What would be the output of this code snippet?&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--NGlaL2HG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/09hfn1rj5y8x0i70ot2f.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--NGlaL2HG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/09hfn1rj5y8x0i70ot2f.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you were able to answer this correctly, Congratulations! You have a good idea about event loop and, task queues. This post is not for you.&lt;/p&gt;

&lt;p&gt;So let’s forget about microtasks and just look at this simple code snippet-&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--HU6KsD04--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lkngbrwrg3f874rqp11d.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--HU6KsD04--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lkngbrwrg3f874rqp11d.PNG" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The output of code snippet would be -&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--oIm5Znyn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jsmrujwomiut5lxigft0.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--oIm5Znyn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jsmrujwomiut5lxigft0.PNG" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Please notice that "Good Night" will be logged after at least 5 seconds. So what happens behind the scenes?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step by Step:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Entire script is added to call stack.&lt;/li&gt;
&lt;li&gt;console.log(“Good Morning”) is executed, and then logged on console.&lt;/li&gt;
&lt;li&gt;setTimeout(() =&amp;gt; ..) is executed and passed on to the web api.&lt;/li&gt;
&lt;li&gt;console.log(“Good Afternoon”) is executed, and then logged on console.&lt;/li&gt;
&lt;li&gt;The call stack is being checked: if it’s empty, the event loop pops and event from the callback queue (in our case the callback function) and push it to call stack.&lt;/li&gt;
&lt;li&gt;console.log(“Good Night”) is executed, and then logged on console.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Since ES6 (JavaScript Standard) was released, it turned to be a big player for async executions in JS. It provided a different way of executing async code, adding a concept called "Microtask Queue" (also called "Job Queue"). We can now call the callback queue "Macrotask Queue", and assign a new layer on top of it.&lt;br&gt;
At the end of every tick of the JavaScript Event Loop, the tasks inside the microtask queue are executed. This new functionality assures us that certain async actions will be added to the microtask queue, therefore executed right after the tick, before the next task in the macro queue.&lt;/p&gt;

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

&lt;p&gt;Now let’s come to &lt;strong&gt;queueMicrotask&lt;/strong&gt;. This function will explicitly put a task in microtask queue. This is what happens when a promise resolves. If you chain multiple then() statements, they will all be put in the microtask queue and are &lt;strong&gt;guaranteed&lt;/strong&gt; to be executed before handling control back to browser’s event loop. So if you keep queuing tasks in the microtask queue forever, your browser will become unresponsive. You can’t click a button, can’t scroll, nothing…, GIFs stop, animations stop etc. The control will never be passed to browser renderer.&lt;/p&gt;

&lt;p&gt;Now let’s try original question again.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--NGlaL2HG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/09hfn1rj5y8x0i70ot2f.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--NGlaL2HG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/09hfn1rj5y8x0i70ot2f.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The output of above code snippet would be -&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Gm_Mf_hA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2bltzz5od21lxtylsxbu.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Gm_Mf_hA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2bltzz5od21lxtylsxbu.PNG" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step by Step Explanation:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The entire script is added to the call stack.&lt;/li&gt;
&lt;li&gt;console.log(1) is executed and then logged on the console.&lt;/li&gt;
&lt;li&gt;setInterval(() =&amp;gt; {..}, 0) is executed and passed on to the web API. The callback function would be added to the task queue after every 0 seconds.&lt;/li&gt;
&lt;li&gt;settimeout(() =&amp;gt; ..) is executed and passed on to the web API. The callback function would be added to the task queue after 0 seconds.&lt;/li&gt;
&lt;li&gt;Promise.resolve().then(() =&amp;gt; ..); is executed and since the promise is resolved directly, the callback would be pushed to job queue.&lt;/li&gt;
&lt;li&gt;queueMicrotask(() =&amp;gt; …) is executed and it also adds the callback to the job queue.&lt;/li&gt;
&lt;li&gt;console.log(8) is executed and then logged on the console.&lt;/li&gt;
&lt;li&gt;Now, the job queue is checked and all the pending tasks are pushed onto the call stack one by one.&lt;/li&gt;
&lt;li&gt;() =&amp;gt; console.log(5) is pushed onto stack and executed.&lt;/li&gt;
&lt;li&gt;&lt;p&gt;() =&amp;gt; { &lt;br&gt;
console.log(6);&lt;br&gt;
queueMicrotask(() =&amp;gt; ..);&lt;br&gt;
} is executed logging 6 on console and adding another callback to job queue.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;() =&amp;gt; console.log(7) is pushed onto stack and executed.&lt;br&gt;
Now since the job queue is empty, the task queue is checked again to see if any task is pending.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;So () =&amp;gt; {  console.log('interval') } is pushed onto stack and executed.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;queueMicrotask(() =&amp;gt; ..) is executed adding callback function to job queue.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;console.log(4); is pushed onto stack and executed.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;() =&amp;gt; {&lt;br&gt;
console.log(2);&lt;br&gt;
        setTimeout( () =&amp;gt; {&lt;br&gt;
            console.log(3);&lt;br&gt;
        clearInterval(interval);&lt;br&gt;
    }, 0);&lt;br&gt;
} is executed logging 2 on console and adding another task to task queue.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;() =&amp;gt; {  console.log('interval') } is pushed onto stack and executed.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;() =&amp;gt; {&lt;br&gt;
console.log(3);&lt;br&gt;
clearInterval(timer);&lt;br&gt;
} is executed logging 3 on console and clearing the interval.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;The important points are:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Tasks are taken from the Task Queue and is called macrotask.&lt;/li&gt;
&lt;li&gt;Microtasks are processed when the current task ends and the microtask queue is cleared before the next macrotask cycle.&lt;/li&gt;
&lt;li&gt;Microtasks can enqueue other microtasks. All are executed before the next task inline.&lt;/li&gt;
&lt;li&gt;UI rendering is run after all microtasks execution.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>eventloop</category>
      <category>async</category>
    </item>
    <item>
      <title>Javascript Concurrency Model</title>
      <dc:creator>Sarthak</dc:creator>
      <pubDate>Thu, 10 Dec 2020 15:27:31 +0000</pubDate>
      <link>https://dev.to/sarthaksam/javascript-concurrency-model-4hod</link>
      <guid>https://dev.to/sarthaksam/javascript-concurrency-model-4hod</guid>
      <description>&lt;h1&gt;
  
  
  Concurreny Model in Javascript
&lt;/h1&gt;

&lt;p&gt;In this article we are going to find out how Javascript implements concurrency and what is event loop and much more...&lt;/p&gt;

&lt;p&gt;So first of all what we all know about Javascrpit is that it is -&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;single-threaded&lt;/strong&gt; which means 2 statements cannot be executed simultaneously,&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;non-blocking&lt;/strong&gt; which means execution of some code should not stop the execution of program because its too slow making the browser unresponsive,&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;asynchronous&lt;/strong&gt; which means that 2 or more tasks can be done simultaneously,&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;concurrent&lt;/strong&gt; means multiple computations can happen at same time.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Since Javascript is single-threaded, then how does it execute statements asynchronously? &lt;/p&gt;

&lt;p&gt;Example code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    console.log("Hello");
    setTimeout( () =&amp;gt; {
        console.log("Hello inside setTimeout");
    }, 1000);
    console.log("Bye");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After executing above statements, browser prints "Hello" and "Bye" first and then "Hello inside setTimeout". &lt;/p&gt;

&lt;p&gt;To find out the answer we need to learn Event Loop first...&lt;/p&gt;

&lt;h1&gt;
  
  
  Event Loop Visualisation
&lt;/h1&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%2Fi%2Fvtk5e1vsf0k09jl8ns7n.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%2Fi%2Fvtk5e1vsf0k09jl8ns7n.png" alt="Alt Text"&gt;&lt;/a&gt;         &lt;em&gt;Fig: Image src: freecodecamp.org&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Heap:&lt;/strong&gt; This is where memory allocation for all your variables take place.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Stack:&lt;/strong&gt; This is where all the javascript code is pushed and gets executed line by line and is popped  out after its execution. Javascript maintain the order of execution contexts using this stack only. It is also known as program stack or execution context stack. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Callback Queue:&lt;/strong&gt; This is the place where all the asynchronous code goes. The callback functions from setTimeout, setInterval, HTML events and ajax requests are pushed into this queue when they are ready for execution.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Event Loop:&lt;/strong&gt; The main function of event loop is to check the program stack and find if it is empty. If the stack is empty, then it checks the callback queue. If the callback queue is not empty then it pushes the code block from callback queue to main stack and executes it sequentially.&lt;/p&gt;

&lt;p&gt;Now lets try to understand what is happening when the above program is getting executed.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The program execution starts. Since Javascript is single threaded only 1 line can be executed at a time.&lt;/li&gt;
&lt;li&gt;So, First line of code is pushed onto stack.&lt;/li&gt;
&lt;li&gt;The console.log is executed printing "Hello". So this line is now popped out of stack.&lt;/li&gt;
&lt;li&gt;Now next line to be executed is setTimeout and it gets pushed onto stack. Now the javascript runtime can only execute single statement but the browser comes with a whole lot of other things which are web apis. This is when concurrency comes into picture. Now on the execution of setTimeout, a call to setTimeout api is made and the setTimeout is now popped of from stack.&lt;/li&gt;
&lt;li&gt;The third statement is pushed onto stack and then executed. This prints "Bye" as output.&lt;/li&gt;
&lt;li&gt;Now when the setTimeout api ( and all other apis ) are completed, the callback is pushed into callback queue simultaneously. These apis cannot interact directly with the stack.&lt;/li&gt;
&lt;li&gt;Now is the time when event loop comes into picture. Event loops jobs is to monitor call stack and task queue. If the call stack is empty, it has to take the first thing from the callback queue and push it onto the stack. So now callback from the timeout is pushed onto the stack which then gets executed and prints "Hello inside setTimeout".&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Exercise Time
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const promise = new Promise((resolve, reject) =&amp;gt; {
  console.log(1);
  setTimeout(() =&amp;gt; {
    console.log("timerStart");
    resolve("success");
    console.log("timerEnd");
  }, 0);
  console.log(2);
});
promise.then((res) =&amp;gt; {
  console.log(res);
});
console.log(4);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output of the above code snippet is -&lt;br&gt;
1&lt;/p&gt;

&lt;p&gt;2&lt;/p&gt;

&lt;p&gt;4&lt;/p&gt;

&lt;p&gt;timerStart&lt;/p&gt;

&lt;p&gt;timerEnd&lt;/p&gt;

&lt;p&gt;success&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Brief Explanation of output&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First of all console.log(1) is executed printing "1".&lt;/li&gt;
&lt;li&gt;Then setTimeout is executed and anonymous function is pushed to Stack and executed.&lt;/li&gt;
&lt;li&gt;Then console.log("timerStart") is executed printing "timerStart".&lt;/li&gt;
&lt;li&gt;Then resolve() is executed thus resolving the promise and the anonymous function from line 66 - 68 is added to callback queue.&lt;/li&gt;
&lt;li&gt;Then console.log(2) is executed.&lt;/li&gt;
&lt;li&gt;Then console.log(4) is pushed to stack and executed.&lt;/li&gt;
&lt;li&gt;Lastly, after the stack is empty the anonymous function from callback queue is pushed to stack and executed.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Some Important facts about event queue-
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt; All the asynchronous code is always executed after the execution of main stack code.&lt;/li&gt;
&lt;li&gt;That is the good part: Your current statements/functions in the stack will run to completion. Async code can not interrupt them. Once your async code is ready to execute, it will wait for main stack to be empty.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  When will you utilize event loop?
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;When you need to do heavy computation which is not required sequentially. In such a case, you would not want to block the main thread.&lt;/li&gt;
&lt;li&gt;When a certain piece of code is to be executed after all the other functions and statements are executed.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
