<?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: Henry Black</title>
    <description>The latest articles on DEV Community by Henry Black (@blackhaj).</description>
    <link>https://dev.to/blackhaj</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%2F411846%2Ffad89bce-20e8-4996-8c20-e6fb596ebe63.jpeg</url>
      <title>DEV Community: Henry Black</title>
      <link>https://dev.to/blackhaj</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/blackhaj"/>
    <language>en</language>
    <item>
      <title>Knee Deep in Javascript: The Javascript Runtime</title>
      <dc:creator>Henry Black</dc:creator>
      <pubDate>Sat, 22 Aug 2020 19:16:24 +0000</pubDate>
      <link>https://dev.to/blackhaj/knee-deep-in-javascript-the-javascript-runtime-3ki2</link>
      <guid>https://dev.to/blackhaj/knee-deep-in-javascript-the-javascript-runtime-3ki2</guid>
      <description>&lt;p&gt;Javascript is a quirky old thing. It divides opinions like no other language, yet it is an integral part of the internet and therefore our lives. Having initially hated it and put off learning it for as long as humanly possible, I am now a doting fan. It's scars and wrinkles have turned to powerful beauty.&lt;/p&gt;

&lt;p&gt;This article is going to look at one high level area: &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;What exactly is happening when you run a piece of code in Javascript?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let's start with a piece of code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;logger&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nf"&gt;logger&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Hello&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We all know that this will print 'Hello' to the console but what happens behind the scenes? For that, we need to understand the Javascript runtime.&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%2Fi%2Foghdnkmbou0czlfhrc1w.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%2Foghdnkmbou0czlfhrc1w.png" alt="The Javascript Runtime"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's start with the execution context. The &lt;strong&gt;Global Execution Context&lt;/strong&gt; is the name for the environment in which javascript parses, stores and executes code. It has two parts:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;The Thread of Execution&lt;/strong&gt; - this is where javascript parses the code line by line, in order.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Global Variable Environment&lt;/strong&gt; (or Global Memory) - this is where javascript stores all the variables and functions that it encounters&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As Javascripts thread of execution parses through our code it does one of two things:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Stores code in the memory - resulting in a label and the stored piece of code (note: when storing the code, Javascript doesn't bother to read it. It just puts it in memory to be accessed later)&lt;/li&gt;
&lt;li&gt;Executes code - this is where Javascript performs an action such as invoking a function. For this, a new Local Execution Context is added onto the call stack and the thread of execution enters the local context&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This brings to attention two points about Javascript:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Javascript is &lt;strong&gt;single threaded&lt;/strong&gt; and &lt;strong&gt;synchronous&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Single threaded:&lt;/strong&gt; Javascript follows one single route through the code rather than taking multiple different routes simultaneously. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Synchronous:&lt;/strong&gt; Javascript processes code in the order that it is presented. Whilst it is processing the current line of code, all the other code has to wait until it is finished&lt;/p&gt;

&lt;p&gt;Let's look at this the context of our code snippet:&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%2Fi%2F2vxs429tjci6wx0gg0r6.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%2F2vxs429tjci6wx0gg0r6.png" alt="Runtime with code"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The thread of execution will pass through our code line by line. The first line it sees is the function definition for logger. Without reading what is inside, Javascript will add that definition to memory under the variable name &lt;code&gt;logger&lt;/code&gt;. Then the thread of execution will move on to the next line of code which is line 5. Here Javascript sees the variable name &lt;code&gt;logger&lt;/code&gt; and checks the global memory to see if there is a variable saved with the same name. There is, so Javascript executes that code, passing in the argument &lt;code&gt;"Hello"&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;When the thread of execution invokes a function, Javascript creates what is called a local execution context.  The &lt;strong&gt;Local Execution Context&lt;/strong&gt; or function level execution context is like a mini Global Execution Context. The thread of execution passes through this local context and can store data in its local memory (the local variable environment). Note: the local context can access the Global Memory but the Global Memory cannot access the Local Memory. This is known as &lt;strong&gt;scope&lt;/strong&gt;. As your programs get more complex, you will likely have many execution contexts nested on top of each other. It's important to remember that that each execution context has access to their own memory and the memory of it's ancestors. When it looks for a variable, if it doesn't find it in it's own execution context Javascript will search the next execution context up and so on until it if finds the variable or throws an error.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Callstack&lt;/strong&gt; keeps track of which context the thread of execution is in. New local execution contexts (known as calls or frames) are pushed onto the stack and when completed they are popped off the stack and the thread of execution returns to the global context. The Callstack is LIFO: last in, first out like a stack of plates - the last one on is always the first on off.&lt;/p&gt;

&lt;p&gt;Given that Javascript is synchronous, multiple blocks of code cannot be executed at the same time. To manage this, Javascript has two queues where asynchronous callbacks wait until the thread of execution is ready for them:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The Callback queue (or task queue)&lt;/li&gt;
&lt;li&gt;The Microtask queue&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;strong&gt;Callback Queue&lt;/strong&gt; and the &lt;strong&gt;Microtask Queue&lt;/strong&gt; are both FIFO: first in, first out. The Microtask queue has higher priority than the Callback queue so its callbacks are executed first. Callbacks from the Callback queue will only be pushed to the stack if the Microtask queue is empty which means too many callbacks in the Microtask queue can starve the callback queue and prevent its tasks from getting onto the callstack.&lt;/p&gt;

&lt;p&gt;The Event Loop is responsible for deciding which callbacks are push onto the stack. It uses two criteria:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Has all the code in the global context been executed?&lt;/li&gt;
&lt;li&gt;Is the callstack empty?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If these criteria are met, it will push callbacks onto the stack.&lt;/p&gt;

&lt;p&gt;So which task makes it into which queue? There are nuances based on each Javascript runtime so let's take a broad brush and assume that we are in the browser. &lt;/p&gt;

&lt;p&gt;There are thee main ways of adding to the Callback queue:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Loading a script from your HTML&lt;/li&gt;
&lt;li&gt;An event fires&lt;/li&gt;
&lt;li&gt;Using &lt;code&gt;setTimout()&lt;/code&gt; or &lt;code&gt;setInterval()&lt;/code&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For the Microtask queue, you have two options:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Resolve or reject a promise&lt;/li&gt;
&lt;li&gt;Use &lt;code&gt;window.queueMicrotask()&lt;/code&gt; (although generally you wouldn't use this unless creating a library/framework)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;That was a whirlwind tour of the Javascript runtime. With this foundational mental model we can move on to learn about hoisting and async Javascript. Part 2 coming up.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
