<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Matthew Mamonov on Medium]]></title>
        <description><![CDATA[Stories by Matthew Mamonov on Medium]]></description>
        <link>https://medium.com/@g.smellyshovel?source=rss-e2c0601c44cf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*NI0ws9EWAhL9CAkk.</url>
            <title>Stories by Matthew Mamonov on Medium</title>
            <link>https://medium.com/@g.smellyshovel?source=rss-e2c0601c44cf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 13:43:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@g.smellyshovel/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What’s new in the ECMAScript 10 (2019)?]]></title>
            <link>https://medium.com/@g.smellyshovel/whats-new-in-the-ecmascript-10-2019-856ed215d47e?source=rss-e2c0601c44cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/856ed215d47e</guid>
            <category><![CDATA[ecmascript10]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ecmascript2019]]></category>
            <category><![CDATA[ecmascript]]></category>
            <dc:creator><![CDATA[Matthew Mamonov]]></dc:creator>
            <pubDate>Wed, 03 Jul 2019 20:35:45 GMT</pubDate>
            <atom:updated>2019-07-03T20:35:45.675Z</atom:updated>
            <content:encoded><![CDATA[<h4>Nothing mindblowing to be fair</h4><p>Many of us thought that some major improvements were gonna be made to ECMAScript with the release of the 10th version of the specification.</p><p>However, they were <strong>not</strong>. All the following proposals are still <strong>stage 3:</strong></p><ol><li>BigInt</li><li>Top-level await</li><li>Promise.allSettled()</li><li>Class accessors, fields and privacy modificators</li></ol><p>And many other interesting ones.</p><p>Instead, editors decided not to rush and thus the 10th version of the specification only presents us with a few quite useful new methods and syntax/semantics improvements. Let’s dive into!</p><p>Array.prototype.flat()</p><p>Flattens a provided array, as it name suggests</p><pre>[[[&quot;nested&quot;, [&quot;arrays&quot;]]], [[&quot;inside&quot;]], [[[&quot;the&quot;]]], [&quot;array&quot;]]<br>-&gt;<br>[&quot;nested&quot;, &quot;arrays&quot;, &quot;inside&quot;, &quot;the&quot;, &quot;array&quot;]</pre><p>The method is not mutating</p><pre>let a = [[1]];<br>a.flat(); // -&gt; [1]<br>a; // -&gt; [[1]]</pre><p>It accepts depth as its sole argument. The default value of depth is 1. The undefined value is also treated to be 1. All the other values are converted to integer (which is gonna evaluate to 0 most of the times)</p><pre>let a = [[1]];</pre><pre>a.flat(1); // -&gt; [1]<br>a.flat(undefined); // -&gt; [1]<br>a.flat(&quot;1&quot;); // -&gt; [1]</pre><pre>let b = [[[2]]];</pre><pre>b.flat(1); // -&gt; [[2]]<br>b.flat(2); // -&gt; [2]<br>b.flat(&quot;2&quot;); // -&gt; [2]<br>b.flat(100); // -&gt; [2]</pre><p>The good thing about the new flat method is that it’s finally presents. No need to implements it manually anymore. The bad thing is that there’s no way to handle arrays of unknown depth with it. You must either use something like Number.MAX_SAFE_INTEGER or recursively invoke the method each time checking whether the target array still contains nested arrays within itself.</p><p>Array.prototype.flatMap()</p><p>The name is a bit confusing though. It seems like it first flattens the input array and then maps it. But in fact it works exactly opposite to that: it first maps the array as it is and only then flattens it and returns the falttened version of the mapped array</p><pre>let a = [[1], [[2]], [[[3]]]];</pre><pre>a.flatMap((item, i) =&gt; item + i); // -&gt; [&quot;10&quot;, &quot;21&quot;, &quot;32&quot;]<br>// but not [1, 3, 5] nor [1, &quot;21&quot;, &quot;32&quot;] as you might&#39;ve expected at first</pre><p>If the provided callback is not callable (i.e. not a function), the TypeError error will be thrown (the same applies to the Array.prototype.map() function as well).</p><p>There’s no way to specify which depth you need to flatten the array to. The depth is slways 1.</p><p>Object.fromEntries</p><p>Object.entries returns an array of arrays composed of key-value pairs of the provided object</p><pre>let a = {<br>  a: 1,<br>  b: 2<br>};</pre><pre>Object.entries(a); // -&gt; [[&quot;a&quot;, 1], [&quot;b&quot;, 2]]</pre><p>Object.fromEntries is essentially opposite to Object.entries — it creates an object from these key-value pairs (entries)</p><pre>let a = [<br>  [&quot;a&quot;, 1],<br>  [&quot;b&quot;, 2]<br>];</pre><pre>Object.fromEntries(a); // -&gt; {a: 1, b: 2}</pre><p>These 2 methods combined can become quite useful to copy objects</p><pre>let a = {<br>  a: 1,<br>  b: 2<br>};</pre><pre>Object.fromEntries(Object.entries(a)) === a; // -&gt; false<br>// a new object is created</pre><p>String.prototype.trimStart() and String.prototype.trimEnd()</p><p>… which are formerly known as trimLeft and trimRight respectively (though these 2 <strong>were</strong> non-standard and now are <a href="http://www.ecma-international.org/ecma-262/#String.prototype.trimleft">added to the specification</a> with the backwards compatibility in mind).</p><p>As their names suggest, theString.prototype.trimStart() trims a target string’s start and the String.prototype.trimEnd() trims a target string’s end.</p><pre>&quot;   Hello   &quot;.trim(); // -&gt; &quot;Hello&quot;<br>&quot;   Hello   &quot;.trimStart(); // -&gt; &quot;Hello   &quot;<br>&quot;   Hello   &quot;.trimEnd(); // -&gt; &quot;   Hello&quot;</pre><p>There’re other minor syntax and semantics improvements as well.</p><p>It’s now legal to omit the catch binding parameters</p><pre>try {<br> throw new Error();<br>} catch { // notice the absence of `()`<br> console.error(“An unknown error occurred”);<br>}</pre><p>Array.prototype.sort() has become “a stable sort”, meaning that if the comparison function returned 0, the initial elements will remain untouched. Previously the behavior was desided by implementations.</p><p>The JSON.stringify method now always returns UTF-8-encoded text regardless of what encoding its input was.</p><p>Implementations since now must return either the actual source text of a function when toString() is invoked on it or a standard placeholder.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=856ed215d47e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The guide on JavaScript’s “this” nightmare]]></title>
            <link>https://medium.com/@g.smellyshovel/the-guide-on-javascripts-this-nightmare-872a4a6a63f4?source=rss-e2c0601c44cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/872a4a6a63f4</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Matthew Mamonov]]></dc:creator>
            <pubDate>Tue, 20 Nov 2018 19:51:15 GMT</pubDate>
            <atom:updated>2018-11-20T19:59:37.007Z</atom:updated>
            <content:encoded><![CDATA[<h4>Yet another way of explaining JavaScript’s “this” keyword behavior. This time in a form of an algorithm.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HCocekYcRvZ9mc0mxKczDQ.png" /></figure><p>Every self-respecting Javascript developer considers it his sacred duty to write a guide on <em>this</em> keyword.</p><p>I decided not to be an exception, having stated all the knowledge on this topic available to me in the form of an algorithm that you can consider as a picture on the left (<a href="https://i.imgur.com/VPgdp2W.png"><strong>click</strong></a> to open it in full size) or interactively <a href="https://www.plectica.com/maps/N1AK4DT9Q"><strong>here</strong></a>.</p><p>In blue are the questions you ask yourself are stated and the answer to which you come asking these questions will be on a card with an orange background.</p><p>“Why <em>in the form of an algorithm</em>?” — you might ask? Well, you know, sometimes such a form of representation is much more convenient for finding an answer to a question of interest more quickly. Maybe it isn’t the easiest way to remember information (at least for some people) but it’s definetly worth it when you just need to obtain an answer.</p><p><em>Wanna read something more verbose from me? Take a look at this giant: “</em><a href="https://medium.com/@g.smellyshovel/the-ecmascript-executable-code-and-execution-contexts-chapter-explained-fa6e098e230f"><em>The ECMAScript “Executable Code and Execution Contexts” chapter explained</em></a><em>”.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=872a4a6a63f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The ECMAScript “Executable Code and Execution Contexts” chapter explained]]></title>
            <link>https://medium.com/@g.smellyshovel/the-ecmascript-executable-code-and-execution-contexts-chapter-explained-fa6e098e230f?source=rss-e2c0601c44cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa6e098e230f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ecmascript]]></category>
            <dc:creator><![CDATA[Matthew Mamonov]]></dc:creator>
            <pubDate>Mon, 19 Feb 2018 18:11:42 GMT</pubDate>
            <atom:updated>2018-10-07T15:36:28.756Z</atom:updated>
            <content:encoded><![CDATA[<h4>The deep dive into the 8th chapter of the ECMAScript specification.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TpMEDUrkSpHAfg9jXjEJtQ.png" /></figure><h3>Table of contents</h3><h4><a href="#a849">Preface</a></h4><ul><li><a href="#f88f">The target audience</a></li><li><a href="#357c">The Map</a></li><li><a href="#4d45">Convensions</a></li><li><a href="#32a4">A little guidance</a></li></ul><h4><a href="#e1b9">1. Agent Cluster</a></h4><ul><li><a href="#aa09">The Agent Cluster is a set of Agents</a></li><li><a href="#abad">Communication between Agents</a></li><li><a href="#7ffe">Summing Up</a></li></ul><h4><a href="#6dfa">2. Agent</a></h4><ul><li><a href="#4738">Executing Thread</a></li><li><a href="#a520">Creating Agents</a></li><li><a href="#e59f">Answering the questions raised in the 1st chapter</a></li><li><a href="#1305">Memory sharing</a></li><li><a href="#960f">Agent Record</a></li><li><a href="#0e14">Summing Up</a></li></ul><h4><a href="#5534">3. Job Queue</a></h4><h4><a href="#ccde">4. Job</a></h4><ul><li><a href="#08dc">Alright, let’s create a new Job</a></li><li><a href="#1f01">Creating ScriptJobs</a></li><li><a href="#a011">Summing Up</a></li></ul><h4><a href="#6e03">5. Execution Context Stack</a></h4><h4><a href="#27f0">6. Execution Context</a></h4><ul><li><a href="#85f3">Execution Context’s State Components</a></li><li><a href="#8529">Creating Execution Contexts</a></li><li><a href="#1478">Violation of the LIFO order</a></li><li><a href="#7e22">Jobs</a></li><li><a href="#b887">Summing Up</a></li></ul><h4><a href="#24eb">7. Realm</a></h4><ul><li><a href="#2180">Summing Up</a></li></ul><h4><a href="#1d49">8. Lexical Environment</a></h4><ul><li><a href="#8f09">Reference to an outer Lexical Environment</a></li><li><a href="#ca07">Function Environment</a></li><li><a href="#c9be">Variable Environment</a></li><li><a href="#c8cd">Global Environment and module Environment</a></li><li><a href="#6be9">Summing Up</a></li></ul><h4><a href="#d0b6">9. Environment Record</a></h4><ul><li><a href="#0a13">Global Environment Record</a></li><li><a href="#9db1">Kinds vs. types</a></li><li><a href="#9605">Declarative Environment Record vs. object Environment Record</a></li><li><a href="#df57">Global Environment Record</a></li><li><a href="#eb10">Object component of the global Environment Record</a></li><li><a href="#229e">Global object</a></li><li><a href="#772a">This and intrinsics</a></li><li><a href="#38ee">Preinitialized properties of the global object</a></li><li><a href="#b218">Runtime-defined properties of the global object</a></li><li><a href="#4b68">Declarative component of the global object</a></li><li><a href="#93d0">Function Environment Record</a></li><li><a href="#c9ed">Variable Environment</a></li><li><a href="#4f9c">Summing Up</a></li></ul><h4><a href="#39c7">In conclusion</a></h4><h3><a href="#a849">Preface</a></h3><p>This article covers such fundamental concepts as the <em>Agent</em>, <em>Agent Cluster</em>, <em>Lexical Environment</em>, <em>Execution Context</em>, <em>Environment Record</em>, <em>Realm</em>, <em>Job</em> and the others. As a “side effect” the <em>Global Object</em> and its records are also considered. In addition to all of the above, some examples of real JavaScript code are also analyzed in terms of what happens at the specification level when they are executed.</p><p>I’d like to mention that by this article I’m not trying to outdo the written in the specification. Nowhere else you can more accurately read about the concepts described by the specification, except than in the specification itself.</p><p>The article is only explanatory, that is, how I personally myself understand the things written in the specification.</p><p>Therefore, do not consider this article as a teaching material. It is better to think of it as an accompanying (auxiliary) material, which you can use to get explanations on the topic of what is written in the specification itself.</p><p>Hence the target audience of this article.</p><h4><a href="#f88f">The target audience</a></h4><p>The article is designed for those who have already started to read the specification, but did not understand anything, and for those who have not even started yet, but probably would have liked very much.</p><p>Therefore, it is desirable that you are very well versed in JavaScript. Otherwise, I can not guarantee that you will understand all the code examples I give.</p><h4><a href="#357c">The Map</a></h4><p>The <a href="https://www.plectica.com/maps/C7Z4HYSNU">Map</a> is your best friend at the time of reading the article. Open it in a separate tab and do not close it until the very end of the article. The Map schematically reflects the relationships between the concepts discussed in this article.</p><p>If you think that you know enough already or you are just too lazy to read all this sheet of text, you can consider exclusively the Map. There is enough information just on it to refresh the specification, or catch a glimpse of what is written in it. All the rest, please just have it around.</p><h4><a href="#4d45">Convensions</a></h4><p>In <em>italic</em> mostly the terms given in the specification are highlighted.</p><p><em>If a whole sentence is shown in italic, it means that the sentence does not relate directly to what the particular section (or chapter) is dedicated to.</em></p><p>In <strong>bold</strong> important words that I wouldn’t want you to miss out on are highlighted.</p><blockquote>Such a quote is a quotation from another source. Basically — from the specification. If the quote is not taken from the specification, then I will mention this, placing the inscription “<em>[Not from the specification]</em>” at the very beginning of the quote.</blockquote><blockquote>The designation “<em>[Composite]</em>” I use in those quotations from the specification, which consist of two parts (more precisely, which I cite as a single quote). I do this so that you don’t try to find the quote in the text of the entire specification. In such cases, it is better to look for the part that stands to the right of the “ — ”.</blockquote><blockquote>If the quote of such kind is used, then I quote either myself (that is, what I said earlier in this article) or another person I communicated with in order to clarify certain points.</blockquote><p>The word “intrinsic” I use as a noun, denoting an “inner property”. Unfortunately, when I found out that “intrinsic” is an adjective, rather than a noun, it was too late. This is due to the fact that in the Russian language (of which I am the bearer), there is a derivative borrowing of this word, which is used precisely as a noun. So I ask you to accept that simply “as is”.</p><p>In this article, I’m talking about the 8th edition of the specification. However, all links pointing to the specification are the links to its “latest” version. Therefore, when a new (most likely, the 9th) edition comes out, some of the links will probably point to the wrong place. Perhaps, I’ll correct this situation in the near future.</p><p>Most of the written in this article is also true for the 6th edition of the specification. Some points are true even for the 5th one.</p><h4><a href="#34a4">A little guidance</a></h4><p>Do not be discouraged if nothing is clear at first. Most likely, understanding will come along with reading, especially taking into account that many of the discussed topics are repeatedly considered later.</p><p>In addition, I advise you to read this article along with the specification (links to the discussed concepts in the specification you can find in the text of the article).</p><h3><a href="#e1b9">1. Agent Cluster</a></h3><p>Let’s begin with the deepest level of abstraction available in the whole <a href="http://www.ecma-international.org/ecma-262/8.0/#sec-executable-code-and-execution-contexts">8th chapter</a> of the specification — the <a href="http://www.ecma-international.org/ecma-262/8.0/#sec-agent-clusters"><em>Agent Cluster</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*FEiuQf-xAkPYpFBJnjF7Sw.png" /><figcaption>Figure 1 — The Agent Cluster card on the <a href="https://www.plectica.com/maps/C7Z4HYSNU">Map</a></figcaption></figure><blockquote>An agent cluster is a maximal set of agents that can communicate by operating on shared memory.</blockquote><p><em>We’re going to get to know Agents in the next chapter of this article.</em></p><p>We can already draw 2 important conclusions right out of the definition above:</p><ol><li>The <em>Agent Cluster</em> is a set of <em>Agents</em>;</li><li><em>The Agents</em> that can communicate with each other by the means of shared memory are always in the same <em>Agent Cluster</em>.</li></ol><h4><a href="#aa09">The Agent Cluster is a set of Agents</a></h4><p>It’s important to understand that the <em>Agent Cluster</em> is just a mechanism used by the specification:</p><blockquote>An agent cluster is a specification mechanism and need not correspond to any particular artefact of an ECMAScript implementation.</blockquote><p>An ECMAscript implementation has to implement not the <em>Agent Clusters</em>, but the <strong>functionality</strong> that these <em>Agent Clusters</em> must provide. So the <em>Agent Cluster</em> may be implemented implicitly, for example, by some kind of intrinsic of an <em>Agent</em> itself, which stores some identificator specifing which <em>Agent Cluster</em> the <em>Agent</em> relies to.</p><pre>// example 1. Abstract programming language</pre><pre>class Agent(agentCluster) {<br>    this.agentCluster = agentCluster; // like this one<br>}</pre><pre>let a1 = new Agent(&quot;C1&quot;);<br>let a2 = new Agent(&quot;C1&quot;);<br>let a3 = new Agent(&quot;C2&quot;);</pre><p>But why does the specification force implementations to devide <em>Agents</em> into <em>Agent Clusters</em>? The answer for this question has already been given in the 2nd conclusion made in the previous section:</p><blockquote><em>Agents</em> that can communicate with each other by the means of shared memory are always in the same <em>Agent Cluster</em>.</blockquote><p>Two <em>Agents</em> must belong to the same <em>Agent Cluster</em> in order to be able to communicate by the means of shared memory:</p><pre>// example 2. Abstract programming language</pre><pre>class Agent(agentCluster) {<br>    this.agentCluster = agentCluster;</pre><pre>    canCommunicate(with, by) {<br>        if (by === &quot;sharedMemory&quot;) {<br>            if (with.agentCluster !== this.agentCluster) {<br>                return false;<br>            }<br>        }</pre><pre>        return true;<br>    }<br>}</pre><pre>let a1 = new Agent(&quot;C1&quot;);<br>let a2 = new Agent(&quot;C1&quot;);<br>let a3 = new Agent(&quot;C2&quot;);</pre><pre>a1.canCommunicate(a2, &quot;sharedMemory&quot;); // true<br>a1.canCommunicate(a3, &quot;sharedMemory&quot;); // false</pre><p>Let me bring you an analogy for a better understanding.</p><p>Imagine a bunch of people (i.e. <em>Agents</em>). Some of this people are deaf-mute and can only communicate with other deaf-mute people using a sign language. Remaining people don’t have such a desease, but they still can only communicate with other people that are not deaf-mute using some natural language.</p><p>In order to devide these people by the available means of communication for a certain man we have to introduce some abstract concept. Such a concept applicable for people might be “groups”. Similarly, the specification introduces the <em>Agent Clusters</em> as “groups” of <em>Agents</em>.</p><p>While a man is something concrete (something we can touch or see) we can’t say the same about a group of men. So applies to the <em>Agent Clusters</em> as well. An <em>Agent</em> is something concrete (at least for now), but the <em>Agent Cluster</em> is not. It’s just a virtual set of <em>Agents</em>.</p><h4><a href="#abad">Communication between Agents</a></h4><blockquote><em>Agents</em> that can communicate with each other by the means of shared memory are always in the same Agent Cluster.</blockquote><p>Remember this second conclusion? As for me so this part raises three more questions:</p><ol><li>Why do <em>Agents</em> need to communicate at all?</li><li>What does <em>“communicate by the means of shared memory”</em> actually mean?</li><li>Are there any other possibilities of communication?</li></ol><p>Let’s begin with the 3d question:</p><blockquote>There may be agents that can communicate by message passing that cannot share memory; they are never in the same agent cluster.</blockquote><p>As you can see, the answer is <strong>yes</strong>. And the possibility for communication exists even for <em>Agents</em> that are not in the same <em>Agent Cluster</em>!</p><p>However, as I mentioned before, such <em>Agents</em> can not share memory. Therefore in order to communicate with each other they have to use some other means of communication. Moreover, such a means can not rely on the use of shared memory. The “<a href="https://en.wikipedia.org/wiki/Message_passing"><em>Message passing</em></a>” means is used for this purpose.</p><p>Anyways, the <em>Agents</em> creation of which we can initiate by the means of code are primarily related to the same <em>Agent Cluster</em>. So we shouldn’t be hammering ourselfs with what the “<em>message passing</em>” represents from itself.</p><p>It is important only to understand that the possibility of communication between <em>Agents</em> from different <em>Agent Clusters</em> exists. And how an implementation implements “<em>message passing</em>”, which provides this possibility, is not particularly important for us.</p><p>And now let’s answer the 2nd question.</p><blockquote>Programs within different agents may share memory by unspecified means. At a minimum, the backing memory for SharedArrayBuffer objects can be shared among the agents in the cluster.</blockquote><p>Memory sharing means that <em>Agents</em> that are in the same <em>Agent Cluster</em> may operate over (i.e. read and write) the same areas of memory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*TZ2sKuMi4GSGgIwrIojAkw.png" /><figcaption>Figure 2 — The abstract representation of the memory sharing means of communication</figcaption></figure><p>Of course, there are special APIs provided in order to opeate over memory. One of such APIs is <em>SharedArrayBuffer objects</em>. Morover the implementation of memory sharing by these objects is described by the specification as a minimum of what each ECMAScript implementation must implement.</p><p><em>We’ll speak more on it in the next chapter.</em></p><blockquote>Programs within different agents may share memory by unspecified means.</blockquote><p>Besides as can be seen from this part of the quote, an implementation may also organize memory sharing by “unspecified” means (APIs). The word “unspecified” here denotes that this means are not defined by the specification, i.e. that an implementation itself along with some other standarts may define them.</p><p>As we’ll see in the next chapter, an implementation usually implements such APIs on top of the <em>SharedArrayBuffer objects</em> API.</p><p>And the last (but not the least) thing: one <em>Agent</em> can belong only to one <em>Agent Cluster</em>, though I’m sure you got it already without my clarifications:</p><blockquote>Every <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a> belongs to exactly one agent cluster.</blockquote><h4><a href="#7ffe">Summing Up</a></h4><ol><li>An <em>Agent Cluster</em> is an abstraction used in the specification in order to divide <em>Agents</em> into “groups” in bounds of which they can share memory with other <em>Agents</em> of this “group”;</li><li><em>Agents</em> that are not in the same <em>Agent Cluster</em> can communicate one with another too. The <em>“message passing”</em> pattern is used in this purpose.</li></ol><h3><a href="#6dfa">2. Agent</a></h3><p>Do you remember my analogy of the <em>Agent Cluster</em>, when I compared it to groups of people? I said there that the <em>Agent</em> is something concrete:</p><blockquote>An <em>Agent</em> is something concrete (at least for now), but the <em>Agent Cluster</em> is not.</blockquote><p>Well, it’s not actually. But let me explain before you throw a stone at me.</p><p><em>Agents</em> really <strong>were</strong> something concrete while we were speaking of <em>Agent Clusters</em>. But they were only because that the <em>Agent Cluster</em> is such a huge abstraction that we just needed something concrete to get hold of.</p><p>But now you must understand that the <a href="http://www.ecma-international.org/ecma-262/#sec-agents"><em>Agent</em></a> is just an abstraction too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*q2H4rAki21ytxeLvb4tgTw.png" /><figcaption>Figure 3 — The Agent card on the <a href="https://www.plectica.com/maps/C7Z4HYSNU">Map</a></figcaption></figure><blockquote>An agent comprises a set of ECMAScript execution contexts, an <a href="http://www.ecma-international.org/ecma-262/#execution-context-stack">execution context stack</a>, a <a href="http://www.ecma-international.org/ecma-262/#running-execution-context">running execution context</a>, a set of named job queues, an Agent Record, and an executing thread.</blockquote><p>In simple words the <em>Agent</em> is some kind of container, encapsulating all the aforecited concepts, that an implementation operates by for the correct interpretation of a code.</p><p><em>Sorting all these concepts out is what we are about to do throughout this article.</em></p><p>Applicable to <em>Agents</em> such concepts are called constituents:</p><blockquote>Except for the <a href="http://www.ecma-international.org/ecma-262/#executing-thread">executing thread</a>, the constituents of an <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a> belong exclusively to that <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a>.</blockquote><p>The <em>Agent</em> in its turn for all of its constituents is called the <em>surrounding Agent</em>:</p><blockquote>While an <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a>’s <a href="http://www.ecma-international.org/ecma-262/#executing-thread">executing thread</a> executes the jobs in the <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a>’s job queues, the <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a> is the surrounding agent for the code in those jobs.</blockquote><p>And don’t be confused by the fact that the specification says that the <em>Agent</em> is the <em>surrounding Agen</em>t for the <strong>code</strong>. I’ll explain what it means later.</p><h4><a href="#4738">Executing Thread</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*AFixMAA8lwgRsdRRsL1Ybg.png" /><figcaption>Figure 4 — The Executing Thread card on the <a href="https://www.plectica.com/maps/C7Z4HYSNU">Map</a></figcaption></figure><blockquote>An <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a>’s <a href="http://www.ecma-international.org/ecma-262/#executing-thread">executing thread</a> executes the jobs in the <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a>’s job queues on the <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a>’s execution contexts independently of other agents, except that an <a href="http://www.ecma-international.org/ecma-262/#executing-thread">executing thread</a> may be used as the <a href="http://www.ecma-international.org/ecma-262/#executing-thread">executing thread</a> by multiple agents, provided none of the agents sharing the thread have an <a href="http://www.ecma-international.org/ecma-262/#agent-record">Agent Record</a> whose [[CanBlock]] property is true.</blockquote><p>The fact that the specification says that the <em>Executing Thread</em> executes <em>Jobs</em> from the <em>Agents</em>’ <em>Job Queues</em> is not 100% exact description of what is happening.</p><p>The <em>Executing Thread</em> itself is not even the specification’s concept. Morover the <em>Executing Thread</em> is not mentioned anywhere outside the chapter dedicated to <em>Agents</em>. And the fact that the <em>Executing Thread</em> does not appear in the algorithms described by the specification does not even worth mentioning.</p><p>It’s way more correct to say that the <em>Jobs</em> of the <em>Agents</em>’ <em>Job Queues</em> are executed <strong>in</strong> a certain <em>Executing Thread</em>.</p><p>You should understand that the code execution consists of parsing and executing separate code nodes. And the execution is a task directly of the interpreter.</p><p>However the code is executed in a certain <em>Executing Thread</em>. But the interpreter is allowed to split the execution between deffirent <em>Executing Threads</em>.</p><p>Therefore when the specification says that this is the <em>Executing Thread</em> who derictly executes the code, then it means that the code is executed (<strong>by</strong> the interpreter) <strong>in</strong> a certain <em>Executing Thread</em>. Nevertheless there is no interpreter exists in terms of the specification, so the <em>Executing Thread</em> is the one who actually executes the code only in terms of the specification.</p><p>Therefore the <em>Executing Thread</em> executes code only in terms of the specification, but not in terms of the common sense.</p><blockquote>But the interpreter is allowed to split the execution between deffirent <em>Executing Threads</em>.</blockquote><p>But wait, you’ve probably heard more than once that JavaScript is a single-threaded programming language? Then what different threads can we talk about?</p><p>JavaScript really is a single-threaded language. However there’re several APIs exist that allow separate scripts to be executed in different threads.</p><p>In this case, as we remember from the previous section, one <em>Executing Thread</em> can be shared by several <em>Agents</em>:</p><blockquote>Except for the <a href="http://www.ecma-international.org/ecma-262/#executing-thread">executing thread</a>, the constituents of an <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a> belong exclusively to that <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a>.</blockquote><p>In other words the code of the <em>Jobs</em> of the <em>Job Queues</em> of separate <em>Agents</em> may be executed by the same <em>Executing Thread</em>. But it’s obvious as well that two separate <em>Executing Threads</em> can not execute the code of the <em>Jobs</em> of the same <em>Agent</em>.</p><p>In addition the <em>Jobs</em>’ codes of separate <em>Agents</em> can be executed in the same <em>Executing Thread</em> only if the <em>[[CanBlock]]</em> property of none of these <em>Agents</em> is <em>true</em>:</p><blockquote>…except that an <a href="http://www.ecma-international.org/ecma-262/#executing-thread">executing thread</a> may be used as the <a href="http://www.ecma-international.org/ecma-262/#executing-thread">executing thread</a> by multiple agents, provided none of the agents sharing the thread have an <a href="http://www.ecma-international.org/ecma-262/#agent-record">Agent Record</a> whose [[CanBlock]] property is true.</blockquote><p><em>We’ll talk more on it in the next section of this chapter.</em></p><h4><a href="#a520">Creating Agents</a></h4><blockquote>While an <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a>’s <a href="http://www.ecma-international.org/ecma-262/#executing-thread">executing thread</a> executes the jobs in the <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a>’s job queues, the <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a> is the surrounding agent for the code in those jobs.</blockquote><p>In essence, the <em>Agent</em> is a sandbox in which some code is executed. And this sandbox gives the code access to all of its constituents so that the code is executed correctly (and executed at all). Morover, the executing code <strong>itself</strong> interacts with the constituents of the <em>surrounding Agent</em>.</p><p>But, as we already know, the code is executed not by itself, but by the <em>Executing Thread</em> (at least in terms of the specification). Therefore, the specification says that the <em>Agent</em> is the <em>surrounding Agent</em> for the code: in other words, the <em>surrounding Agent </em>for the code is the sandbox in which this code is executed.</p><p>Exactly because of this reason a said at the beginning of this chapter that the Agent is the <em>surrounding Agent</em> for all of its constituents:</p><blockquote>The <em>Agent</em> in its turn for all of its constituents is called the <em>surrounding Agent</em>:</blockquote><p>That is, when, for example, an <em>Exection Context Stack</em> is created before the code is executed, the <em>Agent</em> is the <em>surrounding Agent</em> for both the code itself and for the created <em>Execution Context Stack</em>, since the <em>Execution Context Stack</em> is necessary for proper code processing.</p><p>The specification does not describe the creation of <em>Agents</em>, and therefore their creation falls on the shoulders of an implementation. The implementation itself decides when and how to create a new <em>Agent</em>.</p><p>And this is quite logical, because, as you remember, the <em>Agent</em> is an abstraction that comprises other concepts. Thus, the creation of an <em>Agent</em> may not occur at all, but instead, all necessary for the code execution constituents of the <em>Agent</em> may be created, thereby implicitly leading to the creation of the <em>Agent</em> itself.</p><p>The only thing that is mandatory is that every constituent of the <em>Agent</em> must be ready yet before the execution of the code begins.</p><blockquote>Some web browsers share a single executing thread across multiple unrelated tabs of a browser window, for example.</blockquote><p>From this quote it is obvious that the code of separate tabs of a browser refers to separate <em>Agents</em> (although the code from separate tabs (of separate <em>Agents</em>) can be executed by one <em>Executing Thread</em>). In other words, the <em>surrounding Agent</em> for the code that you run in the console of one tab of a browser is one <em>Agent</em>, and is another <em>Agent</em> for the code that you run in the console of another browser tab.</p><p>Anyways, this concerns to a browser, but we are interested in the possibility of creation of a new <em>Agent</em> (the <em>Agent</em> as a specification concept, of course) by the means of code.</p><p>And this can be done, albeit very implicitly. To do so, we need to use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers"><em>Web Workers</em></a><em> </em><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API"><em>API</em></a>.</p><blockquote><em>[Not form the specification]</em></blockquote><blockquote>Web Workers is a simple means for web content to run scripts in background threads.</blockquote><pre>// example 3. JavaScript</pre><pre>// main.js</pre><pre>var myWorker = new Worker(&#39;worker.js&#39;);</pre><pre>myWorker.postMessage(&quot;Hello from master.js!&quot;);</pre><p>And that’s it! We’ve just told our main script to create a new <em>Worker</em> and posted a new message to it…</p><pre>// example 4. JavaScript</pre><pre>// worker.js</pre><pre>onmessage = function(e) {<br>    console.log(`Message from the main script: ${e.data[0]}`);<br>}</pre><p>…and then told the <em>Worker</em> to log this message when it recieves it.</p><p>Sadly enough the further exploration of the <em>Web Workers</em> is beyond the scope of this article. Instead of diving deep into them we’re going to take a look at what we’ve just made from the specification’s point of view.</p><p>Our main script defined a new <em>Worker</em>. Taking into account that <em>Workers</em> execute their code on a separate <em>Executing Thread</em> we can say that we’ve implicitly created the new <em>Executing Thread</em>.</p><p>Considering what has already been said about <em>Executing Threads</em>, one <em>Agent</em> can not belong to separate <em>Executing Threads</em>. Thus, created the new <em>Executing Thread</em> we’ve implicitly created the new <em>Agent</em>!</p><h4><a href="#e59f">Answering the questions raised in the 1st chapter</a></h4><p>Speaking of <em>Web Workers</em> we’ve implicitly answered the question raised in the 1st chapter of this article:</p><blockquote>Why do Agents need to communicate at all?</blockquote><p><em>Agents</em> are usualy tightly related each to another beings, and one <em>Agent</em> (<em>Worker</em>) depends on the data that will be recieved by the other <em>Agent</em> (<em>Worker</em>). Hence we need a way to communicate between this <em>Agents</em>.</p><p>For example a separate <em>Worker</em> can be used in order to make some operations on a database, or to recieve some data using some web API. And this data is almost always going to be used in a main script later, so we need a way to return it back.</p><p>And yeah, there is also a transparent API available in order to post messages back to the main script from the <em>Worker</em>. It just goes beyond the scope of this article.</p><h4><a href="#1305">Memory sharing</a></h4><blockquote>Of course, there are special APIs provided in order to opeate over memory. One of such APIs is <em>SharedArrayBuffer objects</em>. &lt;…&gt; <em>We’ll speak more on it in the next chapter.</em></blockquote><p>I also promised you to talk about the <em>SharedArrayBuffer objects</em>. However <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer">there’s not so much to talk about</a>.</p><p>You must also understand that postMessage() method in the example above has nothing in common with <em>“message passing”</em> means of communication except of the<em> “message passing”</em> means of communication and the postMessage() method use kind of the same concept underneath.</p><p>The real thing here is that the postMessage() method uses <em>SharedArrayBuffer objects</em> as a sort of some underlying API:</p><blockquote><em>[Not from the specification]</em></blockquote><blockquote>To share memory using SharedArrayBuffer objects from one Agent in an Agent Cluster to another &lt;…&gt;, postMessage() and <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">structured cloning</a> is used.</blockquote><p>That is exactly what I told you in the previous chapter:</p><blockquote>As we’ll see in the next chapter, an implementation usually implements such APIs on top of the <em>SharedArrayBuffer objects</em> API.</blockquote><p>The MDN <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer">lets us know</a> that the postMessage() API does’t directly use the <em>“message passing”</em> means of communication. Instead, it uses memory sharing disguied under the <em>“message passing”</em> (as a concept).</p><p>Here’s another quote from the specification that’s worth a mention:</p><blockquote>The agents in a cluster need not all be alive at some particular point in time. If <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a> <strong>A</strong> creates another <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a> <strong>B</strong>, after which <strong>A</strong> terminates and <strong>B</strong> creates <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a> <strong>C</strong>, the three agents are in the same cluster if <strong>A</strong> could share some memory with <strong>B</strong> and <strong>B</strong> could share some memory with <strong>C</strong>.</blockquote><p>The only interesting part for us here is this one:</p><blockquote>The agents in a cluster need not all be alive at some particular point in time.</blockquote><p>That means that the <em>Agent</em> <strong>A</strong> that spawned another <em>Agent</em> <strong>B</strong> may terminate before the <em>Agent</em> <strong>B</strong>, i.e. the <em>Agent</em> <strong>B</strong> may <strong>outlive</strong> the <em>Agent</em> <strong>A</strong>.</p><p>That means that <em>Agents</em> are absolutely independent one to another beings. Sometimes when codes of separate <em>surrounding Agents</em> are executed in separate <em>Executing Threads</em> such independency may lead to undesirable behavior. You can find the example of such undesirable behavior in the “About thread safety” section of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">MDN’s Web Workers guide</a>, if you are interested in it.</p><h4><a href="#960f">Agent Record</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*v9pJzY287Y4Lb1a7nbf43g.png" /><figcaption>Figure 5 — The Agent Record card on the <a href="https://www.plectica.com/maps/C7Z4HYSNU">Map</a></figcaption></figure><p>Remember the definition of the <em>Agent</em>?</p><blockquote>An agent comprises a set of ECMAScript execution contexts, an <a href="http://www.ecma-international.org/ecma-262/#execution-context-stack">execution context stack</a>, a <a href="http://www.ecma-international.org/ecma-262/#running-execution-context">running execution context</a>, a set of named job queues, an Agent Record, and an executing thread.</blockquote><p>As we can see, each <em>Agent</em> has its own <a href="http://www.ecma-international.org/ecma-262/#agent-record"><em>Agent Record</em></a>. Let’s talk more on that.</p><p>We already spoke a little bit about the <em>Agent Record</em> when we were speaking of <em>Executing Threads</em>. Let me bring it to you mind again:</p><blockquote>An <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a>’s <a href="http://www.ecma-international.org/ecma-262/#executing-thread">executing thread</a> executes the jobs in the <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a>’s job queues on the <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a>’s execution contexts independently of other agents, except that an <a href="http://www.ecma-international.org/ecma-262/#executing-thread">executing thread</a> may be used as the <a href="http://www.ecma-international.org/ecma-262/#executing-thread">executing thread</a> by multiple agents, provided none of the agents sharing the thread have an <a href="http://www.ecma-international.org/ecma-262/#agent-record">Agent Record</a> whose [[CanBlock]] property is true.</blockquote><p>The specification doesn’t provide us with the definition of an <em>Agent Record</em> itself. The only thing related to <em>Agent Records</em> in the specification is the <a href="http://www.ecma-international.org/ecma-262/#agent-record">Table 26</a>.</p><p>And this is not accidental, since the <em>Agent</em>’s <em>Agent Record</em> is a real entity exclusively within the specification. Where and how an implementation will store the fields of a certain <em>Agent Record</em> is completely indifferent for the specification.</p><p>As we can see from the <a href="http://www.ecma-international.org/ecma-262/#agent-record">Table 26</a>, the <em>Agent Record</em> is just some sort of a set of properties, used by the <em>Agent</em> in order to store some information about the <em>Agent</em> itself.</p><p>The only interesting for us property of an <em>Agent Record</em> is the <em>[[CanBlock]]</em> property. We spoke a little bit of it already when we were speaking about <em>Executing Thread</em>s. And, for real, an <em>Executing Thread</em> uses this property of an <em>Agent</em>’s <em>Agent Record</em> in order to determine whether a newly-spawned <em>Agent</em> can use the same <em>Executing Thread</em> as an <em>Agent</em> that spawned it or not. The specification explicitly says that two <em>Agents</em> may share the same <em>Exetuting Thread</em> only if none on them <a href="https://nodejs.org/en/docs/guides/blocking-vs-non-blocking/">can block</a> its execution.</p><p>As you propably know already, JavaScript has the non-blocking model as the prior one. This non-blocking model may be achieved using the so-called asyncronous calls.</p><p>But JavaScript also may execute code syncronously. And such a syncronous execution of the code can <strong>block</strong> the execution flood of the thread. But we don’t want to make one <em>Agent</em> <strong>A</strong> to wait for another <em>Agent</em> <strong>B</strong> till it completes it’s execution in order to <em>Agent</em> <strong>A</strong> can begin (or continue) execution of its own code. So here comes the <em>[[CanBlock]]</em> property of an <em>Agent Record</em>.</p><p>If some calls in an <em>Agent</em>’s code can block the execution of this code, then this Agent can not use the same <em>Executing Thread</em> as the <em>Agent</em> that is about to spawn the blocking <em>Agent</em>.</p><p>The considered by me is considered by the specification not far more detailed. Anyway, I suggest you to <a href="http://www.ecma-international.org/ecma-262/#sec-forward-progress">get familiarized</a> with it.</p><p>An <em>Agent Record</em> also has the <em>[[Signifier]]</em> property that is used to identify the <em>Agent</em> in an <em>Agent Cluster</em>. This one always takes a globally unique value.</p><h4><a href="#0e14">Summing up</a></h4><ol><li>The <em>Agent</em> comprises a bunch of stuff, two of which — the <em>Agent Record</em> and the <em>Executing Thread</em> — have been considered in this chapter yet.</li><li>The <em>Agent</em> is an abstraction used in order to tie together all the constituents of the <em>surrounding Agent</em>.</li><li>Separate <em>Agents</em> may share the same <em>Executing Thread</em> under the certain conditions. At the same time one <em>Agent</em> can not belong to different <em>Executing Threads</em>.</li><li>We can implicitly create a new <em>Agent</em> using the <em>Web Workers API</em>.</li><li><em>Agents</em> created via the <em>Web Workers API</em> may communicate with each other by the means of shared memory, which means that they belong to the same <em>Agent Cluster</em>.</li></ol><h3><a href="#5534">3. Job Queue</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*DFADUIIh5IGdIso-SpNQsA.png" /><figcaption>Figure 6 — The Job Queue card on the <a href="https://www.plectica.com/maps/C7Z4HYSNU">Map</a></figcaption></figure><blockquote>A <a href="http://www.ecma-international.org/ecma-262/#agent-record">Job Queue</a> is a FIFO queue of PendingJob records.</blockquote><p>Let’s analyze this definition in parts.</p><blockquote>A Job Queue is a FIFO queue…</blockquote><p>What does “FIFO” mean?</p><p>Well, FIFO stands for the First-In-First-Out type of a queue. That means that the earlier a new <em>Job</em> has entered the <em>Job Queue</em>, the earlier it will become executed.</p><p>You can think of FIFO queue as of a regular queue that you participate in almost everyday: when you stay in line at a bus stop, at a bank, etc.</p><p>There is also a LIFO queue type as an opposite one, but we’ll discuss it later when we need it.</p><blockquote>…queue of PendingJob records.</blockquote><p><em>PendingJob</em> is a regular <em>Job</em>. “Pending” part of the term just shows that <em>Jobs</em> in <em>Job Queues</em> are postponed and are not accomplished yet:</p><blockquote>A PendingJob is a request for the future execution of a Job.</blockquote><p>So the <em>Jobs</em> in the <em>Job Queue</em> are called <em>PendingJobs</em> because they are not yet executed.</p><p><em>We are going to get to know Jobs very soon.</em></p><p>Each <em>Agent</em> has it’s own set of named <em>Job Queues</em>. The specification defines two required types of <em>Job Queues</em>: <em>ScriptJobs Job Queue</em> and <em>PromiseJobs Job Queue</em>, though a concrete ECMAScript implementation is allowed to define additional <em>Job Queues</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*FhkIQQ-DFA3G1qI2Zfwzxg.png" /><figcaption>Figure 7 — The Job Queues of the Agent on the <a href="https://www.plectica.com/maps/C7Z4HYSNU">Map</a></figcaption></figure><p><em>Job Queues</em> are created when the <em>surrounding Agent</em> is created. At a minimum, <em>ScriptJobs Job Queues</em> are initialized before any code is executed by definition, because the code of any script, as we will see later, is essentially represented as a <em>PendingJob</em> record of the <em>ScriptJobs Job Queue</em>.</p><p>Anyways, we can’t speak much more about <em>Job Queues</em> apart from <em>Jobs</em> themselves. So, let’s consider the <em>Job</em> first coming back to <em>Job Queues</em> from time to time.</p><h3><a href="#ccde">4. Job</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*98qQx586bScTdNZ6ujun0A.png" /><figcaption>Figure 8 — The Job card of the <a href="https://www.plectica.com/maps/C7Z4HYSNU">Map</a></figcaption></figure><blockquote>A Job is an abstract operation that initiates an ECMAScript computation when no other ECMAScript computation is currently in progress.</blockquote><p>Here goes an interesting part:</p><blockquote>…when no other ECMAScript computation is currently in progress.</blockquote><p>The specification says that execution of a <a href="http://www.ecma-international.org/ecma-262/#agent-record"><em>Job</em></a> can be initiated only when there is no <em>Running Execution Context</em> and the <em>Execution Context Stack</em> is empty.</p><p>Of course, we can’t turn to <em>Execution Contexts</em> right now, because we haven’t consider them yet. But we’ll do it later. For now let’s just omit this part and assume that this 2 conditions are fulfilled.</p><p>So, what is the <em>Job</em> again? First of all, the <em>Job</em> — is an abstract operation. Abstract over what? Well, it’s abstract over a real code that this <em>Job</em> is about to execute. And this is the main purpose of the <em>Job</em> as of a mechanism.</p><p>The real purpose of the <em>Job</em> is to execute some code later, when there’s nothing else to execute.</p><h4><a href="#08dc">Alright, let’s create a new <em>Job</em></a></h4><p>Well, let is. But… Here’s a little thing that you must understand before doing it. Let’s talk of it first.</p><p>The thing here is that you can not explicitly create a new <em>Job</em> (the <em>Job</em> is just an abstract concept, remember?). But you can create some other stuff which in turn will implicitly create and enqueue the new <em>Job</em>.</p><p>Doesn’t it remind you the things that we’ve spoke about when we were speaking of creating new <em>Agents</em>? Yeah, and it should, because the concept here is the same.</p><p>For example, in JavaScript we can create a new Promise that in terms of the specification will create and enqueue a new <em>PendingJob</em>. So, let’s finally do it.</p><pre>// example 5. JavaScript</pre><pre>new Promise((resolve) =&gt; {<br>    setTimeout(() =&gt; resolve(&quot;Two&quot;));<br>}).then((message) =&gt; {<br>    console.log(message);<br>});</pre><pre>console.log(&quot;One&quot;);</pre><p>Here we implicitly created a new <em>PromiseJob</em>. This Job gets <strong>enqueued</strong> on the <em>PromiseJobs Job Queue</em> of the <em>surrounding Agent</em>. But when will it became executed?</p><p>Well, as we already know, when there will be no <em>Running Execution Context</em> anymore. We’ll consider this condition later, when we’ll speak about <em>Execution Contexts</em> themselves, but for now you can think that this is the same as the end of the main script.</p><p>The main script (i.e. the script which enqueues the new <em>PromiseJob</em>, roughly speaking it is the code of the example 5) is going to be accomplished first, hence the first output of this script — One. Then, when there is nothing else to execute, the first <em>PendingJob</em> of the <em>PromiseJobs Job Queue</em> is removed from this queue and is executed. Hence the second output — Two.</p><p>As you probably understand, Promises themselves are beyond the scope of this article. I won’t even provide you with links to other articles on this topic. There is a very huge amount of material available on the Internet, so you can find something yourself.</p><p>Notice also that the new async functions are also enqueued on the <em>PromiseJobs Job Queue</em>. Moreover, they are kind of based upon the Promise API.</p><blockquote>Once execution of a Job is initiated, the Job always executes to completion.</blockquote><p>While a <em>Job</em> executes the code associated with it, no other <em>Jobs</em> associated with the <em>surrounding Agent</em> may start execution of the code associated with them:</p><blockquote>No other Job may be initiated until the currently running Job completes.</blockquote><p>In other words while an <em>Executing Thread</em> of an <em>Agent</em> executes a <em>Job</em> from this <em>Agent</em>’s <em>Job Queue</em>, it is going to execute it to the very end, and only then can begin to execute another one.</p><blockquote>However, the currently running Job or external events may cause the enqueuing of additional PendingJobs that may be initiated sometime after completion of the currently running Job.</blockquote><p>You must also understand that this only applies to <em>Jobs</em> of <em>Job Queues</em> of <em>Agents</em> sharing the same <em>Executing Thread</em>. For instance, if two <em>Agents</em> are associated with different <em>Executing Threads</em> then these <em>Executing Threads</em> can execute the <em>Jobs</em> of <em>Agents</em>’ <em>Job Queues</em> independently one of another.</p><p>OK, but what about the ScriptJobs Job Queues?</p><h4><a href="#1f01">Creating ScriptJobs</a></h4><p>Frankly speaking initially I planned to avoid the discussion on this topic. Why? Because except of the specification itself there’s no information you can find on it. And even this information provided by the specification is hidden so well, that I couldn’t have been able to answer all the questions that were appearing while I was researching on this topic myself.</p><p>Exactly because of this reason I decided to ask the question on StackOverflow (ru.StackOverflow, to be exact). I was hoping that more diligent and, the most important, more experienced developers would be able to sort it all out for me.</p><p>And it happened. A special thanks goes to <a href="https://stackexchange.com/users/5456992/pavel-mayorov">Pavel Mayorov</a> for helping me to get clear with appearing misconceptions and misunderstandings.</p><p>Lets begin with the <a href="http://www.ecma-international.org/ecma-262/#sec-jobs-and-job-queues">Table 25</a> of the specification. We can see from this table that the <em>Jobs</em> in the <em>ScriptJobs Job Queue</em> validate and evaluate the source of both scripts and modules:</p><blockquote><em>[Composite]</em></blockquote><blockquote>ScriptJobs — Jobs that validate and evaluate ECMAScript Script and Module source text.</blockquote><p>First of all let’s try to draw a parallel between the <em>PromiseJobs Job Queues</em> and the <em>ScriptJobs Job Queues</em>. If we are able to enqueue <em>Jobs</em> on <em>PromiseJobs Job Queues</em> (well, only implicitly, see the section above), then we have to be able to enqueue <em>Jobs</em> on the <em>ScriptJobs Job Queues</em> as well?</p><p>By the way, this is how the title of my SO issue sounds like: “How to initiate a ScriptJob?”</p><p>Of course, when I was asking this question I already knew that modules do also belong to <em>ScriptJobs</em>. But does it mean that in order to enqueue a new <em>PendingJob</em> on the <em>ScriptJobs Job Queue</em> it’s enough just to import some module? Well, sort of…</p><p>Let’s think about what’s going on logically.</p><p>As we know already, a new <em>Job</em> can not begin its execution until the previous one terminates. Let’s imagine that we’ve linked a script to a web page. And this script imports a module and then calls a function defined in this module. What happens in this case?</p><p>As it turned out, the program’s entry point in terms of the specification (or rather in terms of this chapter of the article) is the abstract operation called <a href="http://www.ecma-international.org/ecma-262/#sec-runjobs"><em>RunJobs</em></a>. The meaning of this operation in simple words is to choose those scripts that are destined to be executed and enqueue them on a the <em>ScriptJobs Job Queue</em>. But this operation doesn’t reach its end on that point. The most important step of the <em>RunJobs</em> is to execute the first <em>Job</em> of each <em>Job Queue</em> (of <em>ScriptJobs Job Queue</em> at first, of course).</p><p>So when a browser decides to begin execution of some JavaScript code then it first associates this code with a <em>Job</em>, enqueues this <em>Job</em> on the <em>ScriptJobs Job Queue</em> and only after that begins its execution.</p><p>But wait, what’s about the module itself though? If by importing the module we enqueue it on the same <em>ScriptJobs Job Queue</em> in which the main script executes at this time, then we enqueue it during the execution of the main script’s <em>Job</em>. And as we know so far 2 Jobs can not be executed simultaneously (except if they are executed by different <em>Executing Threads</em>, of course). So why when the main script calls the functions that are imported by the module there’re no errors are thrown, even though the code of the imported module hasn’t been executed yet, which means that none of the imported functions are prepared and can be executed?</p><p>Well, everything’s not as straightforward. Read the definition of the <em>ScriptJobs Job Queue</em> again and try to explain this phenomena yourself first.</p><blockquote>Jobs that validate and evaluate ECMAScript Script and Module source text.</blockquote><p>I’ve missed the most important word in this sentence: “<strong>validate</strong>”.</p><p>The thing here is that all the imports are already resolved by the time the <em>Executing Thread</em> begins execution of the main script (the code of the main script, represented by the <em>Job</em>). Take a look at the 6th step of the procedure <a href="http://www.ecma-international.org/ecma-262/#sec-toplevelmoduleevaluationjob">15.2.1.19</a>.</p><p>So as it turns out, modules are enqueued on the <em>ScriptJobs Job Queues</em> before the the main script (i.e. the one that imports these modules) itself, which means that the code of the modules is executed <strong>by the time</strong> the main script itself is executed.</p><blockquote>Typically an ECMAScript implementation will have its Job Queues pre-initialized with at least one PendingJob and one of those Jobs will be the first to be executed. An implementation might choose to free all resources and terminate if the current Job completes and all Job Queues are empty. Alternatively, it might choose to wait for a some implementation specific <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a> or mechanism to enqueue new PendingJob requests.</blockquote><p>This note of the specification says, that it most likely that some <em>PendingJob</em> will be enqueued on the <em>ScriptJobs Job Queue</em> right on the very moment of the initialization of this <em>Job Queue</em>. And such <em>PendingJob</em> automatically becomes the first one to be executed.</p><p>There’s also said there that a concrete ECMAScript implementation itself decides what to do when there’re no more <em>Jobs</em> left in a <em>ScriptJobs Job Queue</em> (for example, when the main script had done it’s work and no other scripts are linked to a web page). As an option it could free all the occupied resources, or, instead, it could wait until some inner mechanisms enqueue a new <em>PendingJob</em> on the <em>ScriptJobs Job Queue</em>. And this could happen, for instance, in case of presence of several scripts linked to a certain web-page. In such case, when one script ends its work (<em>Executing Thread</em> ends execution of the related <em>Job</em>), implementation doesn’t destroy the <em>Agent</em> (thus destroing the <em>Job Queue</em> as well), but makes it wait until a new <em>PendingJob</em> appears in the <em>ScriptJobs Job Queue</em>.</p><p>So, what we have so far, is that there are the source codes of the related modules which are get enqueued on the <em>ScriptJobs Job Queues</em> as <em>PendingJob </em>records, provided that modules’ source codes are executed before the scripts that import these modules.</p><p>Back to the initial question: how to enqueue a <em>PendingJob</em> on the <em>ScriptJobs Job Queue</em>? Again, there’s no way you can do it (explicitly).</p><p>We distracted pretty much already, so it’s a good time to remind, that <strong>we</strong> don’t create <em>PendingJobs</em>. A <em>Job</em> is just an abstraction over some real code and the <em>Job Queue</em> is just an abstraction used in order to indicate the order of execution of these <em>Jobs</em>.</p><p>Nevertheless, we create new <em>PendingJobs</em> implicitly every time when we import some module into the main script (of course, a new <em>ScriptJob</em> is created in this case, the creation of <em>PromiseJobs</em> we’ve already considered earlier). Moreover, we do so even when we link the main script itself (and not only the main one, of course).</p><p>Finally, as you can see this topic turned out to be quite interesting, and the authors of the other materials on similar topics are in vain avoiding it so diligently.</p><p>The last thing I want to tell you about the <em>Jobs</em> is that the <em>Jobs</em>, just like <em>Agents</em>, each has its own <em>Job Record</em>. But there’s nothing really interesting to discuss in the scope of this article. So just know that each <em>Job</em> on the specification’s level has its own <em>Job Record</em> which stores some intrinsics which are necessary in terms of correct evaluation of the related <em>Job</em>.</p><h4><a href="#a011">Summing Up</a></h4><ol><li>The <em>Job</em> is an abstract concept representing the real code that this <em>Job</em> is about to execute;</li><li>The <em>Job</em>’s code is executed by a certain <em>Executing Thread</em> (or <strong>in</strong> a certain <em>Executing Thread</em> as you remember).</li><li>The <em>Jobs</em> are enqueued on <em>Job Queues</em>;</li><li>Each <em>Agent</em> has at least two named <em>Job Queues</em>: the <em>ScriptJobs Job Queue</em> and the <em>PromiseJobs Job Queue</em>;</li></ol><h3><a href="#6e03">5. Execution Context Stack</a></h3><p>As we know so far, each <em>Agent</em> comprises a bunch of stuff, some of which gets created right after the initialization of the <em>surrounding Agent</em>.</p><p>One of such things along with, for example, the <em>Job Queues</em> is the <a href="http://www.ecma-international.org/ecma-262/#sec-execution-contexts"><em>Execution Context Stack</em></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*nE8MztG3o5pQJEbpYf2l6g.png" /><figcaption>Figure 9 — The Execution Context Stack card on the <a href="https://www.plectica.com/maps/C7Z4HYSNU">Map</a></figcaption></figure><blockquote>The execution context stack is used to track execution contexts.</blockquote><p>Basically the <em>Execution Context Stack</em> is a LIFO stack that is used by the specification to represent the order of creation of new <em>Execution Contexts</em> and evaluation of their code.</p><blockquote>Transition of the <a href="http://www.ecma-international.org/ecma-262/#running-execution-context">running execution context</a> status among execution contexts usually occurs in stack-like last-in/first-out manner.</blockquote><p>First, let’s look at what does <em>Running Execution Context</em> mean.</p><blockquote>At any point in time, there is at most one execution context per <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a> that is actually executing code. This is known as the <a href="http://www.ecma-international.org/ecma-262/#agent">agent</a>’s running execution context.</blockquote><p>And yeah, right, as you probably remember, the <em>Running Execution Context</em> term is also used by the <em>Agent</em>. So how is it related to <em>Execution Context Stack</em> then?</p><p>Everything is exectly opposite in fact. The <em>Running Execution Context</em> is actually <strong>directly</strong> related to the <em>Execution Context Stack</em>, but is just <strong>sidewards</strong> related to the <em>Agent</em>. Roughfly speaking <em>Running Execution Context</em> record of the <em>Agent</em> is just a reference to the concrete <em>Running Execution Context</em> of the <em>Execution Context Stack</em> of the this <em>Agent</em>.</p><blockquote>The <a href="http://www.ecma-international.org/ecma-262/#running-execution-context">running execution context</a> is always the top element of this stack.</blockquote><p>And now let’s sort out what does “LIFO” mean. Even when we were speaking about the <em>Job Queues</em>, I briefly mentioned that the LIFO is the opposite of the FIFO-type <strong>queues</strong>.</p><p>In fact, that is not absolutely correct. Even though LIFO is for real opposite to FIFO term, it doesn’t mean yet that this is the type of a <strong>queue</strong> as well. It comes at least from the LIFO term meaning itself — “Last-In-First-Out”.</p><p>If you think of it logically, then you would quicly understand that there’s no more precise example of LIFO-something than a <strong>stack</strong> itself.</p><p>As an alternative you can also think of LIFO stack as of a heap of something. We can put an object on top of the heap, and when we want to take the object out of the heap, we will involuntarily take the last placed one.</p><p>Of course <strong>we</strong> can not “put” ant “take” <em>Execution Contexts</em> on and from the <em>Execution Context Stack</em> manually. Moreover you don’t even need to do so. All these operations are done by implementations for us. Even though, perhaps, implicitly.</p><p>An implementation may even not implement <em>Execution Context Stacks</em> at all, while tracking the order of <em>Execution Contexts</em> at some lower levels. For instance, by some intrinsics of the <em>Execution Contexts</em> themselves.</p><p>So it’s important to understand that the <em>Exectution Context Stack</em> exists as some independent entity only in terms of the specification.</p><blockquote>However, some ECMAScript features require non-LIFO transitions of the <a href="http://www.ecma-international.org/ecma-262/#running-execution-context">running execution context</a>.</blockquote><p>We will analyze a concrete example in which the LIFO order is actually violated a bit later.</p><p>And now I suggest you to act as we did with the <em>Job</em> and the <em>Job Queue</em>. Let’s get to know the <em>Execution Context</em> first coming back to the <em>Execution Context Stack</em> from time to time. This is needed due to the fact that the further explanations of the <em>Execution Context Stack</em>’s mechanics and manipulations are absolutely pointless without proper understanding of the <em>Execution Context</em> itself.</p><h3><a href="#27f0">6. Execution Context</a></h3><p>Finally we came to the main part of the article. Why I call it main? At least because all the other concepts discussed in this article revolve around the <a href="http://www.ecma-international.org/ecma-262/#sec-execution-contexts"><em>Execution Contexts</em></a>. Moreover, the whole 8th capter of the specification (and this is the part that we’ve been considering throghout the whole article, in case you forgot) is named in honor of the <em>Execution Contexts</em>: “Executable Code and Execution Contexts”. So lets dive right into!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*NmJPfpGy3X0R_lfgT7jIfA.png" /><figcaption>Figure 10 — The Execution Context card on the <a href="https://www.plectica.com/maps/C7Z4HYSNU">Map</a></figcaption></figure><p>First of all, as usual, the definition:</p><blockquote>An execution context is a specification device that is used to track the runtime evaluation of code by an ECMAScript implementation.</blockquote><p>As you remember from the previous chapter, the <em>Execution Context Stacks</em> are used to track the order of execution of the <em>Execution Contexts</em>:</p><blockquote>The execution context stack is used to track execution contexts.</blockquote><p>The <em>Execution Context</em>, in it’s turn, is used to ensure that an ECMAScript implementation could monitor the evalution of the code itself during the runtime. In fact, this is the main purpose of the <em>Execution Context</em>.</p><p>We will analyze the creation of the <em>Execution Contexts</em> and the mechanisms of their operation in the next section of this chapter, and now I propose to dwell in more detail on their internal arrangement.</p><p>If you look at the Figure 10, you will notice that the <em>Execution Context</em> includes quite a few different stuff. Namely, a certain entity called the <em>State Components</em>, and two of the most important records: the <em>Variable Environment</em> and the <em>Lexical Environment</em>.</p><p>We will talk about the <em>Variable Environment</em> and the <em>Lexical Environment</em> in the chapter devoted to the <em>Lexical Environments</em>, and we will talk a little about the <em>State Components</em> right here, but before that I want to mention one important thing.</p><p>In fact, the <em>Lexical Environment</em> and the <em>Variable Environment</em> records of the <em>Execution Context</em> are also its <em>State Components</em>, although in the specification they are separated into a separate group called “Additional State Components”. Nevertheless, on the Map and during this article I present them as 2 completely separate and independent entities of each <em>Execution Context</em>.</p><p>I do this only to emphasize their importance, because from the point of view of the specification and from the point of view of the consideration of this article, the <em>Lexical Environment</em> and the <em>Variable Environment</em> deserve much more attention than the <em>State Components</em> of the <em>Execution Context</em>. Nevertheless, let’s finally move on to the <em>State Components</em>.</p><h4><a href="#85f3">Execution Context’s State Components</a></h4><p>The <em>State Components</em> of the <em>Execution Context</em> are a kind of set of some named internal components inherent in each <em>Execution Context</em>. The <em>State Components</em> can contain as many items as needed, their number depends only on specific implementation’s needs.</p><p>However, the specification describes the four components, which are the absolute minimum of what must be implemented by each implementation. Let’s go through them in order.</p><p><strong>Code evaluation state:</strong></p><blockquote>Any state needed to perform, suspend, and resume evaluation of the code associated with this execution context.</blockquote><p>This, perhaps the main <em>State Component</em> of any <em>Execution Context</em>. As you can see from the definition given by the specification, this component contains a certain state that is used by implementations to evaluate, suspend and continue the execution of the code.</p><p>I would think of the word “state” not as of a “condition”, but rather more like a “structure”. That is, as far as I understand, this component should be used by implementations as some kind of structure containing some information about the execution of a specific code related to a specific <em>Execution Context</em>.</p><p><strong>Function:</strong></p><blockquote>If this <a href="http://www.ecma-international.org/ecma-262/#sec-execution-contexts">execution context</a> is evaluating the code of a function object, then the value of this component is that function object. If the context is evaluating the code of a <a href="http://www.ecma-international.org/ecma-262/#prod-Script">Script</a> or <a href="http://www.ecma-international.org/ecma-262/#prod-Module">Module</a>, the value is null.</blockquote><p>If the code associated with a particular <em>Execution Context</em> is the code of a function, then this component is a kind of reference to the function itself. But if the <em>Execution Context</em> is associated with a module or a script code, then the value of this <em>State Component </em>is <em>null</em>.</p><p>You can also find within the specification such term as <em>Active Function Object</em>. This is simply an alternative name for the <em>Function State Component</em> of the <strong><em>Running</em></strong><em> Execution Context</em>.</p><p>That is, if the <strong><em>Running</em></strong><em> Execution Context</em> evaluates the code of a function, then the <em>Active Function Object</em> refers to the function itself.</p><p><strong>ScriptOrModule:</strong></p><blockquote>The <a href="http://www.ecma-international.org/ecma-262/#sec-abstract-module-records">Module Record</a> or <a href="http://www.ecma-international.org/ecma-262/#script-record">Script Record</a> from which associated code originates. If there is no originating script or module, as is the case for the original <a href="http://www.ecma-international.org/ecma-262/#sec-execution-contexts">execution context</a> created in <a href="http://www.ecma-international.org/ecma-262/#sec-initializehostdefinedrealm">InitializeHostDefinedRealm</a>, the value is null.</blockquote><p>This component contains information about the script or module within which the context-bound code is executed. You can also notice that sometimes (for instance, in the case of creation of the initial <em>Execution Context</em> by the abstract operation <a href="http://ecma-international.org/ecma-262/8.0/#sec-initializehostdefinedrealm"><em>InitializeHostDefinedRealm</em></a>), the value of this component can be <em>null</em>.</p><p><strong>Generator:</strong></p><blockquote>The GeneratorObject that this <a href="http://www.ecma-international.org/ecma-262/#sec-execution-contexts">execution context</a> is evaluating.</blockquote><p>If the code associated with a particular <em>Execution Context</em> is the code of the generator function, then this component contains a reference to the generator function itself. But if the code associated with the <em>Execution Context</em> is not the code of the generator function, then, unlike it was with the <em>Function Component</em>, the value of this component will not be <em>null</em>. This component simply will not exist at all.</p><p><strong>Realm:</strong></p><blockquote>The <a href="http://www.ecma-international.org/ecma-262/#realm-record">Realm Record</a> from which associated code accesses ECMAScript resources.</blockquote><p>We’ll talk in more detail on <em>Realms</em> in a separate chapter devoted directly to them.</p><h4><a href="#8529">Creating Execution Contexts</a></h4><p>Probably, you assumed such a turn of events, in which it turns out that you can not explicitly create a new <em>Execution Context</em>. And, if it really is, then I can congratulate you — you began to understand things and got involved in understanding the specification.</p><p>Anyway, I explain: we can not <strong>explicitly</strong> create a new <em>Execution Context</em>. The <em>Execution Context</em> is only a mechanism used by the specification, which may not even be explicitly implemented by a particular EСMAScript implementation:</p><blockquote>An execution context is purely a specification mechanism and need not correspond to any particular artefact of an ECMAScript implementation. It is impossible for ECMAScript code to directly access or observe an execution context.</blockquote><p>Oh, so little that we can not create an <em>Execution Context</em>, so we can’t even access it or observe it? As it turns out, yes!</p><p>If you suddenly before that time did not understand that some real ECMAScript code (for example, JavaScript) that you actually write does not work directly with the concepts described by the specification, then now is the best time to realize it. When we talk about something within the specification, then we talk about some abstract mechanisms that can only be implemented by some particular ECMAScript implementation, and we can not in any way access (or observe) these mechanisms by the means of our real code.</p><p>Ok, so we can not create an <em>Execution Context.</em> But, let it be purely within the specification, but in some cases it is created? Right you are.</p><p>In fact, a new <em>Execution Context</em> is created every time the control reaches some kind of executable code that is not related to any other <em>Execution Context</em>:</p><blockquote>A new execution context is created whenever control is transferred from the executable code associated with the currently <a href="http://www.ecma-international.org/ecma-262/#running-execution-context">running execution context</a> to executable code that is not associated with that execution context.</blockquote><p>First of all, of course, these are the <em>Jobs</em>.</p><p>When we talked about the <em>Jobs</em>, I said that the <em>Job</em> is a kind of postponed code, which will be executed by the <em>Executing Thread</em> in the future. Yes, this is actually the case, but at the level of the specification and an implementation, everything is a little bit more complicated.</p><p>In fact, none of the code (including the <em>Jobs</em>’ code) is executed by itself. Any code needs a <strong>context</strong> in which this code could be executed. And yes, as you probably already guessed, <em>Execution Context</em> plays the role of such context.</p><p>So every time some code is executed, let it be the code of the main script, or the code of the module, or the code of any other <em>Job</em> (you remember that both the scripts and modules are also represented by <em>Jobs</em>, right?), and even the code of a single function, — to execute such code, a separate <em>Execution Context</em> is created.</p><p>As we remember from the previous section, the main reason for the necessity of having the <em>Execution Contexts</em> per se is that implementations need to somehow track the code evaluation:</p><blockquote>The <em>Execution Context</em>, in it’s turn, is used to ensure that an ECMAScript implementation could monitor the evalution of the code itself during the runtime.</blockquote><p>But why is this necessary?</p><p>The main reason of why an implementation needs to monitor code execution is to create new <em>Execution Contexts</em> and <em>Lexical Environments </em>in a timely manner, as well as to terminate the execution of the code, for example, in case of an exception thrown by a program.</p><p>I suggest taking a look at the specific JavaScript code to see the creation of a new <em>Execution Context:</em></p><pre>// example 6. JavaScript</pre><pre>function recursive(n = 0) {<br>    if (n &gt; 1) throw new Error();</pre><pre>    recursive(++n);<br>}</pre><pre>recursive();<br>console.log(&quot;Will never be logged...&quot;);</pre><p>As we already know, any code of the entire script is represented and is executed in the form of a <em>ScriptJob</em>. And, as I said earlier, a new <em>Execution Context</em> is created (among other things) when a <em>Job</em> is executed:</p><blockquote>In fact, none of the code (including the Jobs’ code) is executed by itself. Any code needs a <strong>context</strong> in which this code could be executed.</blockquote><p>In the specification, my words are confirmed by the fact that before execution of the <em>PendingJobs</em> (which is described in the <a href="http://ecma-international.org/ecma-262/8.0/#sec-runjobs"><em>RunJobs</em></a> abstract operation), the execution of the abstract operation <a href="http://ecma-international.org/ecma-262/8.0/#sec-initializehostdefinedrealm"><em>InitializeHostDefinedRealm</em></a> also takes place, the second step of which is the creation of a new <em>Execution Context</em>:</p><blockquote>2. Let newContext be a new <a href="http://www.ecma-international.org/ecma-262/#sec-execution-contexts">execution context</a>.</blockquote><p>From this it follows that, first of all, the <em>Execution Context</em> is created for the execution of a <em>ScriptJob</em> (by the way, such <em>Execution Context</em> is called the <em>Global Execution Context</em>). This <em>Execution Context</em> immediately becomes the <em>Running Execution Context</em>, because, as we remember:</p><blockquote>The <a href="http://www.ecma-international.org/ecma-262/#running-execution-context">running execution context</a> is always the top element of this stack.</blockquote><p>And in the case of presence of the sole <em>Execution Context</em> in the <em>Execution Context Stack</em>, it’s also the top element of this <em>Execution Context Stack</em> at the same time.</p><p>What happens next?</p><p>The next is the function call. The recursive function, to be more precise. In this case, each time the function is executed, it is executed in a newly-created <em>Execution Context</em>. And yes, even if the same (recursively called) function starts executing:</p><blockquote>Evaluation of code by the <a href="http://www.ecma-international.org/ecma-262/#running-execution-context">running execution context</a> may be suspended at various points defined within this specification. Once the <a href="http://www.ecma-international.org/ecma-262/#running-execution-context">running execution context</a> has been suspended a different execution context may become the <a href="http://www.ecma-international.org/ecma-262/#running-execution-context">running execution context</a> and commence evaluating its code. At some later time a suspended execution context may again become the <a href="http://www.ecma-international.org/ecma-262/#running-execution-context">running execution context</a> and continue evaluating its code at the point where it had previously been suspended.</blockquote><p>In the case of the example 6, it is possible to schematically represent the lifecycle of the <em>Execution Context Stack</em> as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Fx1Y2yTpB5M6-QXClwcnA.png" /><figcaption>Figure 11 — The schematically represented lifecycle of the Execution Context Stack (for the example 6)</figcaption></figure><p>In this case, as you can see, each newly created <em>Execution Context</em> automatically becomes the <em>Running Execution Context</em>:</p><blockquote>The newly created execution context is pushed onto the stack and becomes the <a href="http://www.ecma-international.org/ecma-262/#running-execution-context">running execution context</a>.</blockquote><p>In this example, I did not accidentally decide to exit the recursive function by throwing an exception. The fact is that this is the very case that deserves a separate mention.</p><p>If you run this code in your own environment, you will notice that console.log() in this example will not be executed at all. This is because when an exception is thrown, if it is not caught by any catch block, then the execution of the code terminates. At the same time, an implementation can terminate all the <em>Execution Contexts</em> (including, as we see from the example, the <em>Global</em> one) instantly, without terminating the actual execution of the codes represented by these <em>Execution Contexts</em>.</p><p>By the way, if you run this code, for example, in the Chrome browser, then in the console in addition to the exception message itself, some additional information will also be displayed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*khPRRaoHZRF5uLG__D1rYg.png" /></figure><p>To obtain this information, the implementation refers to the already mentioned earlier <em>State Components</em> of the <em>Execution Context</em>. In particular, in this case, first V8 (Chrome’s JavaScript engine) refers to the <em>Function State Component</em>, outputting the name of the corresponding function, and at the very end to the <em>ScriptOrRealm State Component</em>, outputting, in effect, the <em>Global Execution Context</em> identifier.</p><p>In this particular case, this identifier is “anonymous”, because I executed the script directly from the console, but not from a separate JavaScript file. If you run this code from a separate file, for example, “script.js”, then the exception message might look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*lyg93N8v_RfwV-ZrDDX2Lw.png" /></figure><p>Now I propose to look at the example without throwing an exception:</p><pre>// example 7. JavaScript</pre><pre>function recursive(n = 0) {<br>    if (n &gt; 1) return;</pre><pre>    recursive(++n);<br>    // *<br>}</pre><pre>recursive();<br>console.log(&quot;Will be logged!&quot;);</pre><p>In this example, the <em>Execution Contexts</em> are created in the same order as in the previous one. The only difference is that the return expression completes the execution of the <em>Running Execution Context</em>, removes it from the <em>Execution Context Stack </em>and makes the <em>Running Execution Context</em> the <em>Execution Context</em> beneath it. At the same time, the execution of the code of the new (renewed) <em>Running Execution Context</em> continues from the point the expression before which prompted an implementation to create the new <em>Execution Context</em>. That is, in this case, the execution will continue from the line marked with an asterisk (*) when you exit from recursively called functions and with the console.log() when you exit from a non-recursively called function.</p><p>Schematically, the lifecycle of the <em>Execution Context Stack </em>in the example 7 can be presented as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1u6fRb3XHl6hloP6btcGJw.png" /><figcaption>Figure 11 — The schematically represented lifecycle of the Execution Context Stack (for the example 7)</figcaption></figure><p>In general, it is also quite likely that some optimizations of certain ECMAScript implementations skip the return to the level-lower <em>Execution Context</em>, if it is obvious that there is no more code to execute (as in the case of the string with an asterisk in the example above). But this information is not backed up somehow. It’s just my seemingly well-founded guess.</p><h4><a href="#1478">Violation of the LIFO order</a></h4><p>At the beginning of the chapter, I made a brief mention of the fact that the LIFO order in the <em>Execution Context Stack</em> is not always respected:</p><blockquote>However, some ECMAScript features require non-LIFO transitions of the <a href="http://www.ecma-international.org/ecma-262/#running-execution-context">running execution context</a>.</blockquote><p>However, the specification does not say which “features” exactly.</p><p>Some other authors (I will not name them) of similar materials cite the generator functions as an example. And this is true. But the explanation they give to the question “why?” is incorrect. Let’s try to figure out.</p><p>First of all, I suggest to consider a piece of code in which the work with the generator functions is being carried out:</p><pre>// example 8. JavaScript</pre><pre>function *gen() {<br>    yield 1;<br>    return 2;<br>}</pre><pre>let g = gen();</pre><pre>console.log(g.next().value);</pre><p>Most often, what is happening is explained as follows: when the generator-function is initially called, a new <em>Execution Context</em> is created; when exiting the generator function with the help of the yield statement, the <em>Running Execution Context</em> is not deleted, but simply the “running” status is transferred to the <em>Execution Context</em> that is beneath the current <em>Running Execution Context</em>.</p><p>And even this part is absolutely wrong. First of all, as you remember, the <em>Running Execution Context</em> is <strong>always</strong> the highest element in the <em>Execution Context Stack</em>:</p><blockquote>The <a href="http://www.ecma-international.org/ecma-262/#running-execution-context">running execution context</a> is always the top element of this stack.</blockquote><p>One might assume that this is an inaccuracy in the specification, but no. If you look at the algorithms of the abstract operations describing the execution of the generator function at the specification level (<a href="https://tc39.github.io/ecma262/#sec-generator-abstract-operations">25.3.3</a>), you will notice that the <em>Running Execution Context</em>, created for the execution of this generator function, is <strong>removed</strong> every time we exit the function.</p><p>That is, regardless of what caused the generator function to stop its execution (whether it’s the return statement or the yield statement), the <em>Running Execution Context</em> is first suspended and then deleted.</p><p>The explanation typically continues like the follows: when the generator function is called again, the suspended <em>Execution Context</em> restores its “running” status, i.e. it again becomes the <em>Running Execution Context</em>.</p><p>Again, no. The <em>Running Execution Context</em> of the generator function was not just suspended, but was completely removed. Therefore, there is nothing to restore (or rather there’s no <em>Execution Context</em> anymore to give the “running” status to).</p><p>However, in fact, it was not completely removed (or rather removed, but not completely). It really was removed from the <em>Execution Context Stack</em>, but was saved in the internal <em>[[GeneratorContext]]</em> slot of the generator function.</p><p>The lifecycle of the <em>Execution Context Stack</em> in the example 8 could probably be represented as follows (from the authors’ of the other materials point of view):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lEuB5hVc0wxiEKOQ23feig.png" /><figcaption>Figure 13 — The incorrectly schematically represented lifecycle of the Execution Context Stack (for the example 8)</figcaption></figure><p>But such a representation is incorrect for the reasons described above. In fact, the lifecycle of the <em>Execution Context Stack</em> looks like the follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NUQRCAERlQeGDmUrAKJOVg.png" /><figcaption>Figure 14 — The correctly schematically represented lifecycle of the Execution Context Stack (for the example 8)</figcaption></figure><p>But where is the violation of the LIFO order?</p><p>Well, there’s not.</p><p><a href="https://github.com/allenwb">Allen Wirfs-Brock</a>, one of the editors of the specification (incidentally, it was he who wrote the sentence, which says that the transitions of <em>Running Execution Context</em> may lead to violation of the LIFO order) excellent <a href="https://github.com/tc39/ecma262/issues/1089#issuecomment-362934384">commented</a> on what is happening when working with generator functions.</p><p>The thing here is that he spoke about what is happening not in terms of the <em>Execution Context Stacks</em>, but in terms of procedures:</p><blockquote>With generators, an operation (typically yield) causes an activation record to suspend execution and be removed from the call stack before its associated procedure has terminated execution.</blockquote><p>As it turned out, by that sentence (the one written in the specification) he meant that the violation of the LIFO order means that the <em>Running Execution Context</em> could be terminated (that is, popped out from the <em>Execution Context Stack</em>) far before the <strong>procedure</strong> completed its execution. That is, before the generator function has worked out to the very end. And this is quite logical, because this is the meaning of using generator-functions.</p><blockquote>The removed activation record <em>[i.e. Execution Context]</em> is saved and execution continues using the activation record that was below it on the stack.</blockquote><p>And in this case, as I said earlier, before the removal from the <em>Execution Context Stack</em>, the <em>Running Execution Context</em> is saved, and in the same time the execution of the <em>Execution Context</em> that was in the <em>Execution Context Stack</em> beneath the <em>Running Execution Context</em> (that is, the one that called the generator function) continues.</p><blockquote>At some latter point, an operation (typically the next method) causes a saved activation to be pushed again onto the call stack and its execution resumes at the point where it was suspended. This what I meant by a “non-LIFO” transition.</blockquote><p>When the next method is called, this saved <em>Running Execution Context</em> is restored and pushed onto the very top of the <em>Execution Context Stack</em>, in other words, it becomes the <em>Running Execution Context</em> again.</p><p>Obviously, he found not the most appropriate terms when writing the discussed sentence. In any case, don’t let the presence of this sentence in the specification to bother you. “Non-LIFO transition” does not mean “non-LIFO manupulation with the <em>Running Execution Context</em>”. By this phrase Allen just wanted to say that there are such features of the language that can pop the <em>Running Execution Context</em> out from the <em>Execution Context Stack</em> even before the completion of the procedure associated with this <em>Running Execution Context</em>.</p><h4><a href="#7e22">Jobs</a></h4><p>We have already turned to the <em>Jobs</em> many times in this chapter, and, seems like, have already discussed all the points that I promised to discuss (in the chapter on the <em>Jobs</em> and, possibly, on the <em>Job Queues</em>).</p><p>Nevertheless, there is one topic left that was not discussed yet, and that I would like to say a few words on.</p><p>Remember the definition of the <em>Job</em>?</p><blockquote>A Job is an abstract operation that initiates an ECMAScript computation when no other ECMAScript computation is currently in progress.</blockquote><p>I clarified then what does the “when no other ECMAScript computation is currently in progress” part of the definition mean:</p><blockquote>The specification says that execution of a <em>Job</em> can be initiated only when there is no <em>Running Execution Context</em> and the <em>Execution Context Stack</em> is empty.</blockquote><p>By the way, you can find confirmation of these words in the corresponding section of the specification.</p><p>At the same time I said that we can not take a closer look at what this means, since we do not yet know anything about the <em>Execution Contexts </em>themselves.</p><p>But, as you probably understand, now we have already considered the <em>Execution Context Stack</em>, the <em>Execution Context</em>, and the <em>Running Execution Context</em>, so now we can finally talk about this in more detail.</p><p>First, as I mentioned in the same chapter, the beginning of the execution of the <em>PendingJobs</em> from the <em>Agent</em>’s <em>Job Queues</em> within the specification described in the abstract <em>RunJobs</em> operation:</p><blockquote>As it turned out, the program’s entry point in terms of the specification (or rather in terms of this chapter of the article) is the abstract operation called <a href="http://www.ecma-international.org/ecma-262/#sec-runjobs"><em>RunJobs</em></a>. The meaning of this operation in simple words is to choose those scripts that are destined to be executed and enqueue them on a the <em>ScriptJobs Job Queue</em>. But this operation doesn’t reach its end on that point. The most important step of the <em>RunJobs</em> is to execute the first <em>Job</em> of each <em>Job Queue</em> (of <em>ScriptJobs Job Queue</em> at first, of course).</blockquote><p>However, not only the first <em>Job</em>, as I said then. If we turn to the specification, we will see that the step “j”, which I then spoke about is in the “repeat” block, which means that this step is repetitive and will be performed until the execution of all of the <em>Jobs</em> is finished:</p><blockquote>Perform any implementation or host environment defined job initialization using nextPending.</blockquote><p>But this is just by the way. Back to this part:</p><blockquote>The specification says that execution of a Job can be initiated only when there is no Running Execution Context and the Execution Context Stack is empty.</blockquote><p>I wanted to talk about how the “depletion” of the <em>Execution Context Stack </em>happens. In fact, I did not accidentally mention here the abstract operation <em>RunJobs</em>. The fact is that the termination of the <em>Running Execution Context</em> and, as a consequence, the “depletion” of the <em>Execution Context Stack </em>are also a part of it.</p><p>Initially, <em>RunJobs</em> starts executing the first <em>ScriptJob</em>, which, as we already know, can, for example, add some <em>PromiseJobs</em> to the <em>PromiseJobs Job Queue</em>.</p><p>As it was said earlier, even this very first <em>ScriptJob</em> is not performed by itself. It is performed in the context of a specially created <em>Execution Context</em>. At the same time, during its execution, other <em>PendingJobs</em> could be enqueued on the other queues of the <em>surrounding Agent</em> (for example, on the <em>PromiseJobs Job Queue</em>). And, as you already know, the execution of <em>PendingJobs</em> from these <em>Job Queues</em> can begin only when the <em>Execution Context Stack </em>of this <em>Agent</em> has no <em>Execution Contexts</em> left.</p><p>But at the time of execution of the <em>ScriptJob</em> code, the <em>Running Execution Context</em> does present (it is also the <em>Global Execution Context</em>). Therefore, in order to start executing <em>PendingJobs</em> from the <em>Job Queues</em>, it is necessary to “empty” the <em>Execution Context Stack </em>of the <em>surrounding Agent</em> by terminating the <em>Running Execution Context</em>.</p><p>Termination of the <em>Running Execution Context</em> (i.e. the <em>Global Execution Context</em> in this case), and thus, the complete “depletion” of the <em>Execution Context Stack </em>(after all, the <em>Running Execution Context</em> was the only <em>Execution Context</em> at this time) is described in the step “a” of the “repeat” block of the abstract operation <em>RunJobs</em>:</p><blockquote><a href="http://www.ecma-international.org/ecma-262/#sec-suspend">Suspend</a> the <a href="http://www.ecma-international.org/ecma-262/#running-execution-context">running execution context</a> and <strong>remove</strong> it from the <a href="http://www.ecma-international.org/ecma-262/#execution-context-stack">execution context stack</a>.</blockquote><p>And don’t let the word “suspend” to put you out of countenance. Yeah, at first the <em>Running Execution Context</em> is just gets suspended, but after that, it is explicitly <strong>removed</strong> from the <em>Execution Context Stack</em>, after which there’re no more <em>Execution Contexts </em>left in the <em>Execution Context Stack </em>at all.</p><p>I remind that this process occurs before the execution of <strong>each</strong> <em>Job</em> of all the <em>Job Queues</em> of the <em>surrounding Agent</em> (again, since it is described in the “repeat” block). That is, even when the main script is finished, and when the next script is finished, and when some <em>PromiseJob</em> is finished, and even when some <em>Job</em> from the implementation-defined <em>Job Queue</em> is finished.</p><h4><a href="#b887">Summing Up</a></h4><ol><li>The <em>Execution Context</em> is introduced by the specification as an entity that reflects the state of the evaluation of the code the execution of which happens in this <em>Execution Context</em>.</li><li>Any code is executed in a specific <em>Execution Context</em>.</li><li>The <em>Execution Context</em> is created every time any function is invoked and before the execution of the <em>Jobs</em> from any <em>Job Queue</em> of the <em>surrounding Agent</em> begins.</li><li>The <em>Execution Context Stack</em> monitors the order of creation and evaluation of the <em>Execution Contexts</em>.</li></ol><h3><a href="#24eb">7. Realm</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*GeF-itD4ZggKZJYxHnuh0A.png" /><figcaption>Figure 15 — The Realm card on the <a href="https://www.plectica.com/maps/C7Z4HYSNU">Map</a></figcaption></figure><p>As you know from the previous chapter, the <a href="http://www.ecma-international.org/ecma-262/#sec-code-realms"><em>Realm</em></a> is a record of the <em>Execution Сontext</em>. However, the <em>Realms</em> themselves do not depend on the <em>Execution Сontexts</em>.</p><p>In other words, when an <em>Execution Сontext</em> is created, a new <em>Realm</em> is not created for it. Instead, the <strong>already existing</strong> <em>Realm</em> is associated with the created <em>Execution Сontext</em>.</p><p>But, anyways, there must be a time when a new <em>Realm</em> actually gets created, isn’t it? Right. The creation of the <em>Realm</em> is described by the specification in the abstract operation <a href="http://www.ecma-international.org/ecma-262/#sec-createrealm"><em>CreateRealm</em></a>. But this operation only describes what is happening when creating the <em>Realm</em>, but after all, does the creation itself somehow need to be initiated?</p><p>The request to create a <em>Realm</em> occurs in the previously mentioned abstract operation <em>RunJobs</em>. At the very beginning of execution, this operation performs the other operation <a href="http://www.ecma-international.org/ecma-262/#sec-initializehostdefinedrealm"><em>InitializeHostDefinedRealm</em></a>. And the very first step of this operation is the creation of the new <em>Realm</em>.</p><p>That’s why the specification says that any code should be associated with a <em>Realm</em> <strong>before</strong> evaluation:</p><blockquote>Before it is evaluated, all ECMAScript code must be associated with a realm.</blockquote><p>But why do we need <em>Realms</em>? Why is it created and why is the code associated with it?</p><p>To answer this question, you first need to look at what the <em>Realm</em> is all about:</p><blockquote>Conceptually, a <a href="http://www.ecma-international.org/ecma-262/#realm">realm</a> consists of a set of intrinsic objects, an ECMAScript <a href="http://www.ecma-international.org/ecma-262/#global-environment">global environment</a>, all of the ECMAScript code that is loaded within the scope of that <a href="http://www.ecma-international.org/ecma-262/#global-environment">global environment</a>, and other associated state and resources.</blockquote><p>The specification itself represents the <em>Realm</em> as the <em>Realm Record</em> (by the way, in general any <em>Record</em> is a separate type used by the Specification — the <em>Record</em> type). And the specification describes the components of the <em>Realm Record</em> by the <a href="http://www.ecma-international.org/ecma-262/#table-21">Table 20</a>.</p><p>The <em>Realm Record</em> (that is, the <em>Realm</em> itself) consists of a set of some intrinsics, which are not particularly interesting in the scope of this article, and, most importantly, from the <em>global Environment</em>.</p><p>Therefore, we can say that for us the <em>Realm</em> is some kind of an abstract entity that provides access to the <em>Global Lexical Environment</em> for the <em>Job</em> that is currently in progress.</p><p><em>For now it may not be quite clear what I’m going to talk about, but you can always return to this part later, after you get to know the Lexical Environment and the Environment Record.</em></p><p>If it is very simplistic, then the <em>Realm</em> is created after the <em>Execution Context Stack</em> is created (that is, after the <em>Agent</em> is created), but even before the very first <em>Job</em> of the <em>ScriptJobs Job Queue</em> is executed.</p><p>When the execution of the second <em>Job</em> from the <em>ScriptJobs Job Queue</em> begins, the <em>Realm</em> already exists and provides the code of this <em>Job</em> with access to the already existing <em>global Environment</em> and its <em>global Environment Record</em>.</p><p>The most obvious example, which asks to be brought, is about several scripts linked to a single web page.</p><p>All the scripts are enqueued on the <em>ScriptJobs Job Queue</em>. Before the first script is executed, a new <em>Realm</em> is created, and all the code of all the scripts from the <em>ScriptJobs Job Queue</em> of the <em>surrounding Agent</em> is associated with this newly-created <em>Realm</em>.</p><p>After that, the first script is executed. And in the process of its execution, it has access to the <em>global Environment</em>, which is provided to it by the <em>Realm</em>. The code of this script can interact with the <em>global Environment</em> and, for example, determine some properties in the <em>global Object</em> of this <em>global Environment</em>.</p><p>When the second linked script starts executing, the new <em>Realm</em> is not created for its execution, but the previously created one is used. And that’s why the second linked script can access those new properties that the previous script defined in the <em>global Environment Record </em>of the <em>global Lexical Environment</em>.</p><pre>// example 9. JavaScript</pre><pre>// Note that in this particular example, the order in which scripts are executed may not always be exactly the same</pre><pre>// html<br>&lt;script src=&quot;s1.js&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;s2.js&quot;&gt;&lt;/script&gt;</pre><pre>// s1.js<br>this.a = 1;</pre><pre>//s2.js<br>console.log(a); // 1</pre><p>That is, the <em>Realm</em> is something constant among the inconstancy of constantly creating and retiring <em>Execution Contexts</em>; beginning and completing their execution <em>Jobs;</em> and all the rest of the ongoing chaos. The <em>Realm</em> (among the other things) creates (<a href="http://www.ecma-international.org/ecma-262/#sec-setrealmglobalobject">8.2.3</a>) and fills (<a href="http://www.ecma-international.org/ecma-262/#sec-setdefaultglobalbindings">8.2.4</a>) the <em>global Environment</em>, and later shares it between the various <em>Execution Contexts</em>.</p><p>But why not create it right away when creating a new <em>Agent</em>? In fact, it is likely that some implementations do so. But in any case, the <em>Realm</em> should be associated, as we already know, with an <em>Execution Context</em>. Therefore, although it is created even before the first <em>Execution Context</em> appears in the <em>Execution Context Stack</em>, it is never used separately from the <em>Execution Context</em> (that is, for example, by the <em>Agent</em> itself). It is rather used by the components of the <em>Execution Context</em>, in particular by its <em>Lexical Environment</em>.</p><h4><a href="#2180">Summing Up</a></h4><ol><li>The <em>Realm</em> is represented by the specification as the <em>Realm Record</em>.</li><li>The <em>Realm</em> stores some intrinsics, and, most importantly, provides access to the <em>global Environment.</em></li><li>The <em>Realm</em> is the <em>Execution Context’s record</em> and is used by the constituents of this <em>Execution Context.</em></li><li>The <em>Realm</em> is created before any code is executed and is associated with all the code related to the <em>surrounding Agent</em>.</li></ol><h3><a href="#1d49">8. Lexical Environment</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*m45s3hlXS27mYWqoDRstUw.png" /><figcaption>Figure 16 — The Lexical Environment Card on the <a href="https://www.plectica.com/maps/C7Z4HYSNU">Map</a></figcaption></figure><p>So, first of all I suggest to refer to the specification and take a look at how the <a href="http://www.ecma-international.org/ecma-262/#sec-lexical-environments"><em>Lexical Environment</em></a> is defined there:</p><blockquote>A Lexical Environment is a specification type used to define the association of <a href="http://ecma-international.org/ecma-262/8.0/#prod-Identifier">Identifier</a>s to specific variables and functions based upon the lexical nesting structure of ECMAScript code.</blockquote><p>The <em>Lexical Environment </em>is a kind of a link between identifiers and some real values (data) represented by these identifiers.</p><p>I’m talking about the <em>Lexical Environment</em> precisely as a link, not as some sort of repository for the associations themselves between the identifiers and data, because these associations are not actually stored <strong>directly</strong> in the <em>Lexical Environment</em>. Instead, they are stored in so-called <em>Environment Records</em>.</p><p><em>The next (and at the same time the last) chapter of this article is devoted to the Environment Record.</em></p><p>Then what is the use of the <em>Lexical Environment</em>?</p><p>If you look at the definition one more time, you will notice that these associations are based on the lexical nesting structure of the ECMAScript code:</p><blockquote>…association &lt;…&gt; based upon the lexical nesting structure of ECMAScript code.</blockquote><p>The direct purpose of the <em>Lexical Environment</em> is to enable a certain <em>Environment Record</em>’s data of one <em>Lexical Environment</em> to access the <em>Environment Record</em>’s data of another <em>Lexical Environment</em>. At the same time, as we’ll see shortly, only if that the <em>Lexical Environment</em>, the data of the <em>Environment Record</em> of which is being accessed, is the <strong><em>outer</em></strong><em> Lexical Environment</em> for the <em>Lexical Environment</em> that accesses this data.</p><p>If you look again at the <em>Lexical Environment</em> card on the Map, you will most likely immediately understand what does “based on the lexical nesting structure” mean. But anyway, I’ll explain.</p><p>The fact is that the <em>Lexical Environment</em> consists of the <em>Environment Record</em> and the <strong><em>reference to an outer Lexical Environment</em></strong>:</p><blockquote>A Lexical Environment consists of an <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> and a possibly null reference to an <em>outer</em> Lexical Environment.</blockquote><p>Besides, there are such <em>Lexical Environments</em> may exist, the <em>reference to an outer Lexical Environment</em> of which is <em>null</em>. It’s easy to guess that such <em>Lexical Environments</em> simply don’t have an <em>outer Lexical Environment</em>.</p><blockquote>The outer environment reference is used to model the logical nesting of Lexical Environment values.</blockquote><p>It is the relationship of an <em>outer</em> and a nested <em>Lexical Environments</em> that presents the lexical nesting structure. And at the level of the <em>Lexical Environments</em> themselves, these relationships are represented by the <em>reference to an outer Lexical Environment</em>.</p><p><em>We’ll talk in more detail on how the references to an outer Lexical Environment are used by implementations in the relevant section of this chapter.</em></p><p>There are 3 types of the <em>Lexical Environment</em>: the <em>global Environment</em>, the <em>module Environment</em> and the <em>function Environment</em>.</p><p>It is important to understand that these types are just types of the <strong>specification</strong>. The specification introduces them only so that when describing other mechanisms, it could say that in this particular case it is, for example, the <em>global Environment</em>, and the reader, in turn, already understood how the <em>global Environment</em> differs from the “ordinary” <em>Lexical Environment</em>.</p><p>When I say “ordinary” <em>Lexical Environment</em>, I mean the most usual <em>Lexical Environment</em>, which does not have any differences from the <em>Lexical Environments</em> of the other types in terms of the specification. In fact, the “ordinary” <em>Lexical Environment</em> can be thought of as the referential (standard) one.</p><p>The <em>Lexical Environment</em> of a certain type, in turn, is an extended by some parameters <em>Lexical Environment</em>.</p><p>Exactly because of this reason, to emphasize that the <em>Lexical Environment</em> is always the <em>Lexical Environment</em>, and the <em>global Environment</em>, the <em>module Environment</em> and the <em>function Environment</em> are just its types, I have displayed the leading to them arrows on the Map using the other (green) color.</p><p>As I said, the “ordinary”<em> Lexical Environment</em> can be considered as the referential one. Therefore, before we deal with the differences of the <em>Lexical Environment</em>s of different types, we must first deal with the “ordinary” <em>Lexical Environments</em>.</p><h4><a href="#8f09">Reference to an outer Lexical Environment</a></h4><p>No, the title of this section is not a mistake. The fact is that I promised you to consider in more detail the use of the <em>references to an outer Lexical Environment</em> in a separate section:</p><blockquote><em>We’ll talk in more detail on how the references to an outer Lexical Environment are used by implementations in the relevant section of this chapter.</em></blockquote><p>However, it is impossible to consider how the <em>Lexical Environments</em> use their <em>references to an outer Lexical Environment</em> without considering the <em>Lexical Environments</em> themselves. Therefore, it would be a logical decision to consider them together.</p><p>I also did not want to confuse you, calling this section something like “Ordinary Lexical Environments”, because many of you might think that the “ordinary” <em>Lexical Environment</em> is a separate type of the <em>Lexical Environment</em>, even though I emphasized that there are only 3 types, and the “ordinary” <em>Lexical Environment</em> is<em> </em>just a referential (standard) for all of them.</p><p>Yeah, in fact, the <em>references to an outer Lexical Environment</em> are used by <em>Lexical Environments</em> themselves, or more precisely, they are used to model the logical nesting of separate <em>Lexical Environments</em>:</p><blockquote>The outer environment reference is used to model the logical nesting of Lexical Environment values.</blockquote><p>As some blocks in your real code can surround other blocks of this code, so one <em>Lexical Environment</em> can logically surround another <em>Lexical Environment</em>. Moreover, each block of the code is represented by a separate <em>Lexical Environment</em>.</p><p>Let’s move from verbal abstractions to concrete examples.</p><pre>// example 10. JavaScript</pre><pre>function foo() {<br>    let a = 1;</pre><pre>    {<br>        let b = 2;</pre><pre>        console.log(a, b);<br>    }<br>}</pre><p>In this example, I define a block. Any ECMAScript block defines a new scope for declarations inside this block.</p><p>Every time we define a new scope, we implicitly create a new Lexical Environment. Thus, when the control is transferred to the block, the new Lexical Environment is immediately created.</p><p>All the ECMAScript bindings are statically scoped. Within the specification and within the scope of this article, the word “statically” is synonymous with the word “lexically”. That’s why the <em>Lexical Environment</em> is called the <strong><em>Lexical</em></strong><em> Environment</em>. But what does “statically” (or “lexically”) mean?</p><blockquote><em>[Not from the specification]</em></blockquote><blockquote>A Static Scoping is a kind of scoping, in which we can accurately determine the value of a certain binding in the inner scope, knowing only what value the binding has in the outer scope.</blockquote><p>In other words, only a glance at the code of the function foo in the example 10 is enough to determine the value of the variable a used in the block that is declared in this function.</p><blockquote>The direct purpose of the <em>Lexical Environment</em> is to enable a certain <em>Environment Record</em>’s data of one <em>Lexical Environment</em> to access the <em>Environment Record</em>’s data of another <em>Lexical Environment</em>. At the same time, as we’ll see shortly, only if that the <em>Lexical Environment</em>, the data of the <em>Environment Record</em> of which is being accessed, is the <strong><em>outer</em></strong><em> Lexical Environment</em> for the <em>Lexical Environment</em> that accesses this data.</blockquote><p>This is how I described the main purpose of the <em>Lexical Environment</em> when we first started to get acquainted with them. But thanks to what is this opportunity provided?</p><p>It is easy to guess that the possibility of communication between various <em>Lexical Environments</em> is provided precisely because of the <em>reference to an outer Lexical Environment </em>presence in the <em>Lexical Environments</em>.</p><p>In the example 10, the <em>reference to an outer Lexical Environment</em> of the block’s <em>Lexical Environment</em> points to the <em>Lexical Environment</em> of the function in which the block is defined (the foo function).</p><p>That’s why when we access the variable a inside the block, we do not get an error message.</p><p>First of all, an implementation tries to get the value of the variable a from the <em>Environment Record</em> of the <em>Lexical Environment</em> of the block itself. When it finds that there is no record in the <em>Environmental Record</em> about the variable a, it refers to the <em>reference to the outer Lexical Environment</em> of the current <em>Lexical Environment</em> and looks for a record about the variable a in the <em>Environment Record</em> of the <em>outer Lexical Environment</em>.</p><p>But when the implementation tries to get the value of the variable b, it succeeds in doing this already by referring to the <em>Environment Record</em> of the <em>Lexical Environment</em> of the block itself.</p><blockquote>The outer reference of a (inner) Lexical Environment is a reference to the Lexical Environment that logically surrounds the inner Lexical Environment.</blockquote><pre>// example 11. JavaScript</pre><pre>function foo() {<br>    {<br>        console.log(a);<br>    }<br>}</pre><p>In cases where it’s impossible to determine the value of a variable even after following the entire chain of <em>references to an outer Lexical Environment</em>, in these cases the ReferenceError error is thrown, as in the example 11.</p><blockquote>An outer Lexical Environment may, of course, have its own outer Lexical Environment.</blockquote><p>In fact, this is the case in both examples. The <em>outer Lexical Environment</em> (for the <em>Lexical Environment</em> of the block), that is, the <em>Lexical Environment</em> of the function foo, also has the <em>reference to an outer Lexical Environment</em>. In these cases, the <em>outer Lexical Environment</em> for the <em>Lexical Environment</em> of the function is the <em>global Environment</em>. I spesifically did not mention that moment (and I will not do anymore in this section) simply because a separate section of this chapter is devoted to the <em>global Environment</em>.</p><p>By the way, I just unintentionally gave an example of what I was talking about a little bit earlier:</p><blockquote>It is important to understand that these types are just types of the <strong>specification</strong>. The specification introduces them only so that when describing other mechanisms, it could say that in this particular case it is, for example, the <em>global Environment</em>, and the reader, in turn, already understood how the <em>global Environment</em> differs from the “ordinary” <em>Lexical Environment</em>.</blockquote><p>Instead of saying something like:</p><blockquote>In these cases, the outer Lexical Environment for the Lexical Environment of the function was the Lexical Environment created at the beginning of the code execution, the context for which was the Execution Context created at the beginning of the execution of the scriptJob, which represents the entire code of the above script…</blockquote><p>I just said:</p><blockquote>In these cases, the outer <em>Lexical Environment</em> for the <em>Lexical Environment</em> of the function is the <em>global Environment</em>.</blockquote><p>And although such a comparison is not entirely correct, at least due to the fact that we are not yet familiar with the features of the <em>global Environment</em>, this still emphasizes the convenience of separating the <em>Lexical Environments</em> into types. But now it’s not about that.</p><blockquote>A Lexical Environment may serve as the outer environment for multiple inner Lexical Environments.</blockquote><p>After this quote, the specification also gives its own example for this case. But I will give my own, because for a correct understanding of the example from the specification, it is first necessary to get acquainted with the <em>function Environment</em>.</p><pre>// example 12. JavaScript</pre><pre>function foo() {<br>    let a = 1;</pre><pre>    {<br>        console.log(a)<br>        a++;<br>    }</pre><pre>    {<br>        console.log(a)<br>    }<br>}</pre><p>In this case, the <em>refenrences to an outer Lexical Environment</em> of both <em>Lexical Environments</em> (blocks’), point to the same <em>Lexical Environment</em> — the <em>Lexical Environment</em> of the function foo.</p><p>In addition, from the example 12, one more important conclusion can be drawn: the value of the variable of the <em>Environment Record</em> of the <em>outer Lexical Environment</em> can be changed from the inner <em>Lexical Environment</em>. Such bindings, whose value can be changed, are called mutable bindings.</p><p>The opposite of them are immutable bindings. It is not difficult to guess that as an example of immutable binding we can give a constant declared with the const keyword.</p><p>Besides, the value of a constant (i.e. of an immutable binding) can not be changed not only when it is accessed from an inner <em>Lexical Environment</em>, but also when it is accessed from the same <em>Lexical Environment</em>, in which it is defined:</p><pre>// example 13. JavaScript</pre><pre>// accessing from the inner Lexical Environment<br>function foo() {<br>    const a = 1;</pre><pre>    {<br>        a++;<br>    }<br>}</pre><pre>// accessing from the Lexical Environment, in which the constant is defined<br>function foo() {<br>    const a = 1;<br>    a++;<br>}</pre><p>An attempt to execute the code of the example above ends with a TypeError error message.</p><p>If you remember, in the chapter on the <em>Execution Context</em> I said that the <em>Lexical Environment</em> is the record of the <em>Execution Context</em>:</p><blockquote>If you look at the Figure 10, you will notice that the <em>Execution Context</em> includes quite a few different stuff. Namely, a certain entity called the <em>State Components</em>, and two of the most important records: the <em>Variable Environment</em> and the <em>Lexical Environment</em>.</blockquote><p>And yes, at the same time I also mentioned that both the <em>Variable Environment</em> and the <em>Lexical Environment</em> are also <em>Execution Context</em>’s <em>State Components</em>, though I represented them as separate records for the narrative sequence and simply because they are much more important than the other <em>State Components</em>:</p><blockquote>In fact, the <em>Lexical Environment</em> and the <em>Variable Environment</em> records of the <em>Execution Context</em> are also its <em>State Components</em>, although in the specification they are separated into a separate group called “Additional State Components”. Nevertheless, on the Map and during this article I present them as 2 completely separate and independent entities of each <em>Execution Context</em>.</blockquote><p>In addition, in the same chapter I also said the following:</p><blockquote>The main reason of why an implementation needs to monitor code execution is to create new <em>Execution Contexts</em> and <em>Lexical Environments </em>in a timely manner, as well as to terminate the execution of the code, for example, in case of an exception thrown by a program.</blockquote><p>Now I thought that you could misunderstand me. Saying this, I did not mean that a new <em>Lexical Environment</em> is created <strong>only</strong> when creating a new <em>Execution Context</em>.</p><p>You already know that new <em>Execution Contexts</em> are not created when, for example, a code of a block is executed. But, when the control is transferred to the block, as we have recently reviewed, the new <em>Lexical Environment</em> <strong>is</strong> created.</p><p>And from this it follows that the <em>Lexical Environment</em> record of the <em>Running Execution Context</em> can change during the execution of the code associated with this <em>Running Execution Context</em>.</p><p>For example, you can look at the <a href="http://ecma-international.org/ecma-262/8.0/#sec-block-runtime-semantics-evaluation">13.2.13</a> section of the specification, which describes what is happening with the <em>Lexical Environment</em> and the <em>Execution Context</em> at the time the control is transferred to the block.</p><p>It is clear from this algorithm that at the moment of transferring the control to the block, the current <em>Lexical Environment</em> record of the <em>Running Execution Context</em> is saved, after which, as we already know, a new <em>Lexical Environment</em> is created, the <em>reference to an outer Lexical Environment</em> of which points to the <strong>saved</strong> <em>Lexical Environment</em>. The block’s code is executed in the context of the <em>Running Execution Context</em> with the “swapped” <em>Lexical Environment</em>, and then, once the block completes its execution, the saved <em>Lexical Environment</em> again becomes the <em>Lexical Environment</em> record of the <em>Running Execution Context</em>.</p><p>It is important to understand that implementations themselves decide how and in what form they preserve “old” <em>Lexical Environments</em> before creating a new one. By the way, such a preservation is called <strong>capturing</strong> in another way. That is, in other words, the implementation <strong>captures</strong> the “old” <em>Lexical Environment</em> before creating a new one.</p><h4><a href="#ca07">Function Environment</a></h4><p>In all the examples I gave in the previous section of this chapter, when defining the function foo, a new <em>Lexical Environment</em> was created each time as well. Such a <em>Lexical Environment</em> created for a function is called the <em>function Environment</em>.</p><blockquote>A function environment is a Lexical Environment that corresponds to the invocation of an ECMAScript function object.</blockquote><p>In all the examples from the previous section, we defined the blocks to create new <em>Lexical Environments</em>. As I’ve already said, the block does not generate a new <em>Execution Context</em>. This is the reason for the <em>Lexical Environment</em> created to execute the code of the block to substitute the already existing <em>Lexical Environment</em> record of the <em>Running Execution Context</em>.</p><p>However, to execute a <strong>function</strong>, a new <em>Execution Context</em> is created. Immediately after its creation a new <em>Lexical Environment</em> has to be assigned to the <em>Lexical Environment</em> record of the <em>Running Execution Context</em>. That is why the specification says that the <em>function Environment</em> is the <em>Lexical Environment</em> that is created when the function is called.</p><p>Or rather, it says that this is the <em>Lexical Environment</em> that <strong>corresponds</strong> to the function call. What does it mean?</p><p>Remember my definition of static scoping, which I gave in the previous section?</p><blockquote>A Static Scoping is a kind of scoping, in which we can accurately determine the value of a certain binding in the inner scope, knowing only what value the binding has in the outer scope.</blockquote><p>In other words, if a nested (inner) function refers to a variable defined in an outer function, then we don’t have to know <strong>how</strong> the nested function is called to determine what value the variable will have.</p><pre>// example 14. JavaScript</pre><pre>function foo() {<br>    let a = 1;<br>    <br>    function bar() {<br>        makeSomethingWith(a);<br>    }<br>}</pre><p>It does not matter how the function bar is called. We can always say with a confidence that the value of the variable a inside it is always equals 1.</p><p>Nevertheless, the ECMAScript defines one (and the only one) “variable”, the value of which is scoped dynamically. And such a variable is this.</p><blockquote>A <a href="http://www.ecma-international.org/ecma-262/#function-environment">function environment</a> may establish a new <strong>this</strong> binding.</blockquote><p>As you can see, it is the <em>function Environment</em> who determines the value of the this inside a function.</p><p>But what does “scoped dinamically” means?</p><blockquote><em>[Not from the specification]</em></blockquote><blockquote>A Dynamic Scoping is a kind of scoping, in which the value of a certain binding in the inner scope does not depend on what value the binding has in the outer scope. The dynamic scoping is the complete opposite of the static scoping.</blockquote><pre>// example 15. JavaScript</pre><pre>function foo() {<br>    console.log(this === obj); // true</pre><pre>    function bar() {<br>        console.log(this === obj); // false<br>    }</pre><pre>    bar();    <br>}</pre><pre>let obj = {<br>    a: 1,<br>    foo<br>};</pre><pre>obj.foo();</pre><p>The function bar absolutely doesn’t care what value this had in the foo function’s scope, because the value of this is determined by the <em>Lexical Environment</em> of the bar function.</p><p>And the state of the <em>Lexical Environment</em> of the function bar (that is, the <em>function Environment</em>) depends only on <strong>how</strong> the function bar is called:</p><blockquote>A function environment is a Lexical Environment that corresponds to the invocation of an ECMAScript function object.</blockquote><p>In the previous section, when I said that the <em>references to an outer Lexical Environment</em> of several (inner) <em>Lexical Environments</em> can refer to the same <em>Lexical Environment</em>, I said that I will bring my own example instead of the specification’s one:</p><blockquote>After this quote, the specification also gives its own example for this case. But I will give my own, because for a correct understanding of the example from the specification, it is first necessary to get acquainted with the <em>function Environment</em>.</blockquote><p>The example itself looks like this:</p><blockquote>For example, if a <a href="http://www.ecma-international.org/ecma-262/#prod-FunctionDeclaration">FunctionDeclaration</a> contains two nested <a href="http://www.ecma-international.org/ecma-262/#prod-FunctionDeclaration">FunctionDeclaration</a>s then the Lexical Environments of each of the nested functions will have as their outer Lexical Environment the Lexical Environment of the current evaluation of the surrounding function.</blockquote><p>If I’d brought this example thereat, then you definitely would be embarrassed by this part:</p><blockquote>…of the current evaluation of the surrounding function.</blockquote><p>And this would be quite natural, because as I said in the previous section, all the ECMAScript bindings are statically scoped:</p><blockquote>All the ECMAScript bindings are statically scoped.</blockquote><p>But, as we already know, there is also one value (this), which is scoped dynamically. That is why the specification says that <em>references to an outer Lexical Environment</em> of <em>function Environments</em> of nested functions point to the same <em>Lexical Environment</em>, which is determined by <strong>how</strong> the function is called (that is the “current evaluation of the surrounding function”).</p><p>However, in the example cited by the specification, this part could be omitted.</p><pre>// example 16. JavaScript</pre><pre>function foo() {<br>    let a = 1;</pre><pre>    function bar() {<br>        console.log(a);<br>        a++<br>    }</pre><pre>    function baz() {<br>        console.log(a);<br>    }</pre><pre>}</pre><p>This could be so, at least because the this binding’s value is the only value that is scoped dynamically. And, as we already know, due to the fact that the value of this is scoped dynamically, the nested functions don’t matter what is the value of the this binding in the outer function at all.</p><p>So, if the example that is given by the specification looked like this:</p><blockquote><em>[Not from the specification]</em></blockquote><blockquote>For example, if a <a href="http://www.ecma-international.org/ecma-262/#prod-FunctionDeclaration">FunctionDeclaration</a> contains two nested <a href="http://www.ecma-international.org/ecma-262/#prod-FunctionDeclaration">FunctionDeclaration</a>s then the Lexical Environments of each of the nested functions will have as their outer Lexical Environment the Lexical Environment of the surrounding <a href="http://www.ecma-international.org/ecma-262/#prod-FunctionDeclaration">FunctionDeclaration</a>.</blockquote><p>Then I could easily include it in the previous section of this chapter. And so I just decided not to confuse you.</p><p>In general, the value of the this binding is not always scoped dynamically. But we’ll talk about this in more detail in the next chapter of the article.</p><p>The fact that the <em>function Environment</em> provides a value for the this binding is only one of the 2 differences between the <em>function Environment</em> and the “ordinary” <em>Lexical Environment</em>.</p><p>The second difference is that the <em>function Environment</em> also includes some stuff that is needed to support the super invokations:</p><blockquote>A <a href="http://www.ecma-international.org/ecma-262/#function-environment">function environment</a> also captures the state necessary to support <strong>super</strong> method invocations.</blockquote><p>We’ll talk more on that in the chapter on the <em>Environment Record</em>.</p><h4><a href="#c9be">Variable Environment</a></h4><p><em>Note that this section does not describe any type of the Lexical Environment.</em></p><p>In the previous chapter, when we considered the <em>Execution Context</em>, I said that in addition to the <em>Lexical Environment</em>, each <em>Execution Context</em> also contains the <em>Variable Environment</em>. Moreover, I recalled this even under this chapter:</p><blockquote>If you look at the Figure 10, you will notice that the Execution Context includes quite a few different stuff. Namely, a certain entity called the State Components, and two of the most important records: the Variable Environment and the Lexical Environment.</blockquote><p>So what is the <em>Variable Environment</em>? First of all, the <em>Variable Environment</em> is the <em>Lexical Environment</em> as well:</p><blockquote>The LexicalEnvironment and VariableEnvironment components of an execution context are always Lexical Environments.</blockquote><p>But instead of thinking of it as a separate type of the <em>Lexical Environment</em> (along with the <em>function Environment</em>, the <em>module Environment</em> and the <em>global Environment</em>), it’s better to think of it as the second, additional <em>Lexical Environment</em> of the <em>Execution Context</em>.</p><p>When a new <em>Execution Context</em> is created, a new <em>Lexical Environment</em> and a new <em>Variable Environment</em> are also created for this <em>Execution Context</em>. Moreover, these 2 records are initially absolutely identical:</p><blockquote>When an execution context is created its LexicalEnvironment and VariableEnvironment components initially have the same value.</blockquote><p>Confirmation of these words can be found in the <a href="http://www.ecma-international.org/ecma-262/#sec-ecmascript-function-objects-call-thisargument-argumentslist">9.2.1.1</a> clause of the specification, which describes what happens when a function is called:</p><blockquote>8. Let localEnv be <a href="http://www.ecma-international.org/ecma-262/#sec-newfunctionenvironment">NewFunctionEnvironment</a>(F, newTarget).</blockquote><blockquote>9. Set the LexicalEnvironment of calleeContext to localEnv.</blockquote><blockquote>10. Set the VariableEnvironment of calleeContext to localEnv.</blockquote><p>But it is not entirely correct to think of these operations as assigning the same ECMAScript object to two different variables, because if 2 such variables throughout their lifecycle (or until they are overridden) point <strong>to the same</strong> object, then the <em>Lexical Environment</em> and the <em>Variable Environment</em> records are only initially identical, which means that their states in the future can and, most likely, will differ.</p><p>But why would the <em>Execution Context</em> have at once 2 <em>Lexical Environments</em>? Why is not one enough?</p><p>In order to answer this question, let’s take a look at the <a href="http://www.ecma-international.org/ecma-262/#table-23">Table 22</a>, which describes the <em>Lexical Environment</em> and the <em>Variable Environment</em> components of the <em>Execution Context</em>.</p><blockquote><em>[Composite]</em></blockquote><blockquote>LexicalEnvironment: Identifies the <a href="http://www.ecma-international.org/ecma-262/#sec-lexical-environments">Lexical Environment</a> used to resolve identifier references made by code within this <a href="http://www.ecma-international.org/ecma-262/#sec-execution-contexts">execution context</a>.</blockquote><p>The specification does not specify identifiers created by what code exactly (by which expressions, constructions) are related to the <strong><em>Lexical</em></strong><em> Environment</em> of the <em>Execution Context</em>.</p><blockquote><em>[Composite]</em></blockquote><blockquote>VariableEnvironment: Identifies the <a href="http://www.ecma-international.org/ecma-262/#sec-lexical-environments">Lexical Environment</a> whose <a href="http://www.ecma-international.org/ecma-262/#sec-lexical-environments">EnvironmentRecord</a> holds bindings created by <a href="http://www.ecma-international.org/ecma-262/#prod-VariableStatement">VariableStatement</a>s within this <a href="http://www.ecma-international.org/ecma-262/#sec-execution-contexts">execution context</a>.</blockquote><p>But it says that only the identifiers declared as <em>VariableStatements</em> (that is, using the var keyword) are included to the <strong><em>Variable</em></strong><em> Environment</em>’s <em>Environment Record</em>. It follows from this that identifiers declared in any other way (for example, using the let and const keywords) are related to the <strong><em>Lexical</em></strong><em> Environment</em>’s <em>Environment Record</em>.</p><p>If we turn to the <a href="http://www.ecma-international.org/ecma-262/#sec-declarations-and-the-variable-statement">13.3</a> section of the specification, we would find there a confirmation of my words:</p><blockquote><em>let</em> and <em>const</em> declarations define variables that are scoped to the <a href="http://www.ecma-international.org/ecma-262/#running-execution-context">running execution context</a>&#39;s LexicalEnvironment.</blockquote><p>Accordingly for variables declared using the var keyword:</p><blockquote>A <em>var</em> statement declares variables that are scoped to the <a href="http://www.ecma-international.org/ecma-262/#running-execution-context">running execution context</a>&#39;s VariableEnvironment.</blockquote><p>But now a fairly reasonable question arises: what is the reason under such a separation?</p><p>One of the reasons is historical. The fact is that prior to the 6th version of the specification, the <em>Variable Environment</em> record of the <em>Execution Context</em> served in completely different purposes, the consideration of which goes far beyond the scope of this article. And with the advent of the 6th version of the specification, getting rid of the <em>Variable Environment</em> would be quite problematic, if only because in this case implementations would have to rewrite the tremendeous amount of their code.</p><p>In the same 6th version of the specification, the let and const keywords were added, the variables (or, respectively, the constants) declared using which work in a slightly different manner. The consideration of the differences between them, alas, is also beyond the scope of this article. However, apparently, the editors of the specification decided to kill two birds with one stone: they left both the <em>Lexical Environment</em> and the <em>Variable Environment</em>, and simultaneously kept backward compatibility, and solved the problem with different manner of work of differently declared variables.</p><p>For the sake of completeness, let’s still consider at least one specific reason for the separation of the <em>Lexical Environments</em> on the <em>Lexical Environments</em> and the <em>Variable Environments</em>, described by the current version of the specification.</p><p>eval. The variables defined in the eval’s body using the var keyword are defined in the <em>Environment Record</em> of the <strong><em>Variable</em></strong><em> Environment</em> (of the scope) in which the eval is called:</p><pre>// example 17. JavaScript</pre><pre>function foo() {<br>    eval(&quot;var a = 1;&quot;);<br>    console.log(a);<br>}</pre><pre>foo();</pre><p>Note that this is not the case, if the code of the function and/or the code of the eval is the strict mode code:</p><blockquote>The eval code cannot instantiate variable or function bindings in the variable environment of the calling context that invoked the eval if the calling context is evaluating formal parameter initializers or if either the code of the calling context or the eval code is <a href="http://www.ecma-international.org/ecma-262/#sec-strict-mode-code">strict mode code</a>. Instead such bindings are instantiated in a new VariableEnvironment that is only accessible to the eval code.</blockquote><p>If the variable is declared inside eval using the let or const keyword, then such variable will always refer to the <strong><em>Lexical</em></strong><em> Environment</em> of the eval itself:</p><pre>// example 18. JavaScript</pre><pre>function foo() {<br>    eval(&quot;let a = 1;&quot;);<br>    console.log(a);<br>}</pre><pre>foo();</pre><p>Execution of the code of the example above will result in a ReferenceError error, because the variable a does not exist neither in the <em>Lexical Environment</em> of the function foo, nor in its <em>Variable Environment</em>, nor outside the function.</p><p>By the way, I just unintentionally raised a new question: how does an implementation know where to look for the value associated with a specific identifier when the identifier is accessed — to the <em>Lexical Environment</em> or to the <em>Variable Environment</em>?</p><p>The implementation actually does not know. It seeks both here and there until it finds (or not). However, it is likely that certain implementations optimize the search in every possible way, for example, by storing somewhere some sort of a table, in which it is known in advance which variable is stored where.</p><p>Anyway, when I talk about the <em>Lexical Environment</em> of some <em>Execution Context</em> in this and in the next chapter, I might mean both directly the <em>Lexical Environment</em> and the <em>Variable Environment</em> (of course, except when I explicitly indicate that I’m talking about the <em>Variable Environment</em>). Such a liberty is quite acceptable, especially taking into account that the <em>Variable Environment</em> and the <em>Lexical Environment</em> are both the <em>Lexical Environments</em>.</p><p>The <em>Variable Environment</em> is just called differently so that the specification does not have to use notations like “Lexical Environment 1” and “Lexical Environment 2”. Moreover, the <em>Variable Environment</em> explicitly indicates that the variables declared by what keywords are related to it, which is quite convenient.</p><p>In fact, the <em>Variable Environment</em> is in some cases used by implementations for other purposes. We will talk about one of them in more detail after we get acquainted with <em>Environment Records</em>. Moreover, the variables declared using the var keyword are not always stored in the <em>Environment Record</em> of the <em>Variable Environment</em>. But about this a little later too.</p><p>And now let’s return to the two remaining types of the <em>Lexical Environment</em>.</p><h4><a href="#c8cd">Global Envronment and module Environment</a></h4><p>I decided to combine the <em>global Environment</em> and the <em>module Environment</em> into one section for two reasons:</p><ol><li>First of all, there is not so much to say about them under this chapter to devote a separate section to each of them.</li><li>Secondly, because they are quite similar, as we’ll see in the near future.</li></ol><p>Well, the <em>global Environment</em>.</p><blockquote>A global environment is a Lexical Environment which does not have an outer environment. The <a href="http://www.ecma-international.org/ecma-262/#global-environment">global environment</a>’s outer environment reference is null.</blockquote><p>In fact, this is the main (and only) difference of the <em>global Environment</em> from the “ordinary” <em>Lexical Environment</em>. The <em>global Environment</em> is therefore called “global”, because the global scope is kind of a parantal scope for every other one.</p><pre>// example 19. ECMAScript</pre><pre>// here&#39;s the GLE</pre><pre>function foo() {<br>    // the foo&#39;s FLE</pre><pre>    function bar() {<br>        // the bar&#39;s FLE<br>        <br>        function baz() {<br>            // the baz&#39;s FLE</pre><pre>            {<br>                 // and the block&#39;s LE<br>            }</pre><pre>        }</pre><pre>    }</pre><pre>}</pre><p>Whatever <em>Lexical Environment</em>, from the created in the example above, we would not decide to consider, it is always possible to get to the <em>global Environment</em> accessing the <em>refences to an outer Lexical Environment</em>.</p><p>However, with regard to the <em>global Environment</em>, its <em>reference to an outer Lexical Environment</em> is <em>null</em>. And this is quite logical, because there must be some <em>Lexical Environment</em> that is the main one, that is from which all the other <em>Lexical Environments</em> “grow”, like trees grow from the root.</p><p>The situation with the <em>module Environment</em> is almost the same:</p><blockquote>A module environment is a Lexical Environment that contains the bindings for the top level declarations of a <a href="http://www.ecma-international.org/ecma-262/#prod-Module">Module</a>.</blockquote><p>The <em>module Environment</em> is a <em>global Environment</em> for all declarations inside it. In other words, it is the <em>global Environment</em> of the module itself.</p><p>For example, if the code of a main script looks as follows:</p><pre>// example 20. ECMAScript</pre><pre>var a;<br>let b;<br>const c;</pre><pre>function foo() {}</pre><p>Then all the declared bindings belong to the <em>global Environment</em>. But if the bindings were declared inside the body of the module, then these bindings would refer to the <em>module Environment</em> of the <em>Execution Context </em>the evaluation of the code of this module is associated with.</p><p>But what is the difference between the <em>module Environment</em> and the <em>global Environment</em> after all?</p><p>Their main difference lies in the fact that the <em>module Environment</em>, unlike the <em>global Environment</em>, <strong>has</strong> the <em>reference to an outer Lexical Environment</em>. And this <em>outer Lexical Environment</em> of the <em>module Environment</em> is the <em>global Environment</em> itself!</p><blockquote>The outer environment of a <a href="http://www.ecma-international.org/ecma-262/#module-environment">module environment</a> is a <a href="http://www.ecma-international.org/ecma-262/#global-environment">global environment</a>.</blockquote><pre>// example 21. JavaScript</pre><pre>// main.js<br>let a = 1;</pre><pre>// module.js<br>console.log(a); // 1</pre><p>But the code of the following example (22) will throw the ReferenceError error (think why, the reason is obvious and has already been repeatedly discussed):</p><pre>// example 22. JavaScript</pre><pre>// main.js<br>console.log(a);</pre><pre>// module.js<br>let a = 1;</pre><p>Of course, there are still some things relating to both the <em>global Environment</em> and the <em>module Environment</em>, which I’d like to discuss. But the fact is that these things refer more to the <em>Environment Records</em> of these <em>Lexical Environments</em>. Therefore, we will discuss them in the next chapter.</p><p>And under this chapter, I would like to recall that the <em>global Environment</em> is a record of the <em>Realm</em> of a certain <em>Execution Context</em>. It’s very important to remember.</p><p>The <em>global Environment</em> is not “one-off”. It is used by many <em>Execution Contexts</em> during the execution of the code associated with them. In other words, it is created once for the whole “concern” of the code (that is, the code associated with one <em>Realm</em>). But considering what code refers to the same <em>Realm</em>, unfortunately, is beyond the scope of this article, at least because it’s determined by implementations (or by some other specifications).</p><h4><a href="#6be9">Summing Up</a></h4><ol><li>The <em>Lexical Environment</em> is a record of the <em>Execution Context</em>.</li><li>The <em>Lexical Environment</em> is an encapsulation of the <em>Environment Record</em> and the <em>reference to an outer Lexical Environment</em>.</li><li>The <em>reference to an outer Lexical Environment</em> is used to model the lexical nesting structure of some real code.</li><li>The <em>Lexical Environment</em> can be one of the three types (or not be of any of them at all). Each type somehow differs from the others.</li></ol><h3><a href="#d0b6">9. Environment Record</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*JS86GY9OZrFrO_APFqbXuQ.png" /><figcaption>Figure 17 — The Environment Record card on the <a href="https://www.plectica.com/maps/C7Z4HYSNU">Map</a></figcaption></figure><blockquote>An <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> records the identifier bindings that are created within the scope of its associated Lexical Environment.</blockquote><p>You already know from the previous chapter, that declarations made in the scope of a certain <em>Lexical Environment</em> are not actually stored directly in this <em>Lexical Environment</em>. Instead, the <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records"><em>Environment Record</em></a> of the <em>Lexical Environment</em> serves as such a “repository”.</p><p>But in fact this is not the only purpose of the <em>Environment Record</em>. On the other hand, the <em>Environment Record</em> presents some internal entries (intrinsics) of the <em>Lexical Environment</em> itself. That is, as it was with, for example, the <em>Agents</em> and the <em>Agent Records</em>.</p><p>However, unlike the <em>Agent Records</em>, <em>Environment Record</em>’s intrinsics play a much bigger role for us than the intrinsics of the <em>Agent</em>. But why I say so, we’ll see later.</p><p>As in the case of the <em>Lexical Environments</em>, there are several types of <em>Environment Records</em>. I intentionally do not cite a specific number, but I say “several” because at first glance it is rather difficult to understand how many of them actually are.</p><p>The specification says that there are 2 main kinds of the <em>Environment Record</em>:</p><blockquote>There are two primary kinds of Environment Record values used in this specification: declarative Environment Records and object Environment Records.</blockquote><p>In addition to the <em>declarative Environment Record</em> and the <em>object Environment Record</em>, there are 3 more types of the <em>Environment Record</em>: the <em>function Environment Record</em>, the <em>global Environment Record</em> and the <em>module Environment Record</em>. But the most interesting part begins further when the specification gives an example of how the relationships between them can be described by an implementation:</p><blockquote>For specification purposes Environment Record values are values of the <a href="http://www.ecma-international.org/ecma-262/#sec-list-and-record-specification-type">Record</a> specification type and can be thought of as existing in a simple object-oriented hierarchy where Environment Record is an abstract class with three concrete subclasses, declarative Environment Record, object Environment Record, and global Environment Record.</blockquote><p>It is interesting here that the specification puts the <em>global Environment Record</em> on a par with the <em>declarative Environment Record</em> and the <em>object Environment Record</em>, as if making it clear that there are in fact 3 main kinds of the <em>Environment Record</em> rather than 2. However, there is a specific explanation for that. But before we can proceed to it, we must first deal with the <em>function Environment Record</em> and the <em>module Environment Record</em>.</p><p>First of all, let’s return to the example from the specification:</p><blockquote>Function Environment Records and module Environment Records are subclasses of declarative Environment Record.</blockquote><p>Pretty straightforward, isn’t it? No. Well, yes.</p><p>The <em>function Environment Record</em> and the <em>module Environment Record</em> are for real related to the <em>declarative Environment Record</em>. But the problem is that this example specification gives as a description of how the <em>Environment Records</em> can be described by implementations.</p><p>You, as just a reader of the specification, but not an ECMAScript implementator, can be misled by the word “subclass”. This word can make you think of the <em>function Environment Record</em> and the <em>module Environment Record</em> as of subtypes of the <em>declarative Environment Record</em>. And this is the part that is not entirely correct.</p><p>First, let’s agree on a terminology. Speaking of the <em>declarative Environment Record</em> and the <em>object Environment Record</em>, I used the word <strong>kind</strong>. And speaking of the <em>function Environment Record</em> and the <em>module Environment Record</em>, I used the word <strong>type</strong>. And this is not accidental. At least under this article, I want you to distinguish the types and kinds of the <em>Environment Record</em>. Let’s agree that <em>declarative</em> and <em>object</em> are the kinds, and <em>function</em> and <em>module</em> are the types.</p><p>But why is this necessary?</p><p>The thing is that any of the implicitly created during the code evaluation <em>Environment Record</em> is always either <em>declarative</em> or <em>object</em>. There is no such an “ordinary”, “referential” <em>Environment Record </em>that exists by itself as it was with the <em>Lexical Environment</em>.</p><p>Besides, if an <em>Environment Record</em> is the <em>declarative</em> one, then it can also have a certain type. In particular, the <em>Environment Record</em> can be either the <em>function Environment Record</em> or the <em>module Environment Record</em> in this case.</p><p>But what about the <em>global Environment Record</em>?</p><h4><a href="#0a13">Global Environment Record</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*ThPc4lTdOO_KzxirYq6a5g.png" /><figcaption>Figure 18 — The global Environment Record card on the <a href="https://www.plectica.com/maps/C7Z4HYSNU">Map</a></figcaption></figure><blockquote>For specification purposes Environment Record values are values of the <a href="http://www.ecma-international.org/ecma-262/#sec-list-and-record-specification-type">Record</a> specification type and can be thought of as existing in a simple object-oriented hierarchy where Environment Record is an abstract class with three concrete subclasses, declarative Environment Record, object Environment Record, and global Environment Record.</blockquote><p>In the previous section, I said that it’s interesting that the specification puts the <a href="http://www.ecma-international.org/ecma-262/#sec-global-environment-records"><em>global Environment Record</em></a> on a par with the <em>declarative Environment Record</em> and the o<em>bject Environment Record</em>, although only <em>declarative</em> and <em>object Environment Records</em> are considered to be the <strong>kinds</strong> of the <em>Environment Record</em>:</p><blockquote>There are two primary kinds of Environment Record values used in this specification: declarative Environment Records and object Environment Records.</blockquote><p>In addition, if you noticed, in the previous section I myself did not attributed the <em>global Environment Record</em> neither to the kinds nor to the types. But why?</p><p>First of all, because the <em>global Environment Record</em> is both the kind and the type simultaneously. Let’s turn to the specification:</p><blockquote>A global <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> is logically a single record but it is specified as a composite encapsulating an object <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> and a declarative <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a>.</blockquote><p>First of all, the <em>global Environment Record</em> combines both the o<em>bject Environment Record</em> and <em>declarative Environment Record</em>. If we could divorce ourselfs from everything that has been said above, except for the quote itself, the <em>global Environment Record</em> unwittingly appears as the parent of the <em>declarative</em> and the o<em>bject Environment Records</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*UGitN29gJjSYd_3BNiG7Fw.png" /><figcaption>Figure 19 — The schematic representation of the relationships between the global Environment Record and the declarative and object Environment Records</figcaption></figure><p>But this is completely wrong. Do not forget about the example from the specification, in which all three are presented as the separate kinds:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*T-3K3ju1cQQRyqALrFP-Iw.png" /><figcaption>Figure 20 — The schematic representation of the relationships between the global Environment Record and the declarative and object Environment Records (from the specification’s example point of view)</figcaption></figure><p>As it seems to me, the most logical variant of the schematic representation of all the kinds and the types of the <em>Environment Record</em> can be the following one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uiTR753gyI32SEVvSksoDQ.png" /><figcaption>Figure 21 — The schematic representation of the relationships between the kinds and the types of the Environment Record</figcaption></figure><p>Here we agree that the kinds are in the upper row, and the types are in the lower row.</p><p>However, such a scheme has one serious drawback: it does not show what the <em>global Environment Record</em> is like as a kind.</p><p>Finally, I decided to choose such a schematic representation, which is the one displayed on the Map:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*WtAAbfdolpGJ204Chmv7aA.png" /><figcaption>Figure 22 — The schematic representation of the relationships between the kinds and the types of the Environment Record (the final revision)</figcaption></figure><p>The <em>global Environment Record</em> stands in the bottom row to show that it is a <strong>type</strong> of the <em>Environment Record</em>. At the same time, the two arrows that go <strong>from</strong> it to the <em>declarative</em> and <em>object Environment Records</em> just emphasize that the <em>global Environment Record</em> is also the <strong>kind</strong> consisting of both the <em>declarative</em> and <em>object</em> components.</p><p>But why I did not do so, you might ask:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1yycC-qeGCyx8eyUsU2zFA.png" /><figcaption>Figure 23 — The schematic representation of the relationships between the kinds and the types of the Environment Record (quite incorrect)</figcaption></figure><p>In fact, I just did not want to confuse you. Let me remind you that the specification as the 2 main kinds of the <em>Environment Record</em> provides only the <em>declarative</em> and <em>object Environment Records</em>:</p><blockquote>There are two primary kinds of Environment Record values used in this specification: declarative Environment Records and object Environment Records.</blockquote><p>At the same time, the <em>global Environment Record</em> is a “simulated” kind created by the specification with the aim of combining 2 components at once: the <em>declarative</em> one and the <em>object</em> one.</p><p>As a result, it can be said that the <em>global Environment Record</em> is the <strong>type</strong> of the <em>Environment Record</em>, represented by the <strong>kind</strong> of the same name, which comprises the <em>declarative</em> and the <em>object</em> components.</p><p>At the moment, there is another problem: we have already divided the <em>Environment Records</em> into kinds and types, but we still do not know how they differ from each other. Let’s deal with it.</p><h4><a href="#9db1">Kinds vs. types</a></h4><p>It is important to understand that the specification clearly provides only 2 <strong>kinds</strong> of <em>Environment Records</em>:</p><blockquote>There are two primary kinds of Environment Record values used in this specification: declarative Environment Records and object Environment Records.</blockquote><p>The specification does not name the <em>function</em>, <em>module</em> and <em>global</em> <em>Environment Records</em> as <strong>types</strong>, as I do in the article. Instead, it says that the <em>function</em> and <em>global</em> <em>Environment Records</em> are specializations:</p><blockquote>Global Environment Records and function Environment Records are specializations that are used for specifically for <a href="http://www.ecma-international.org/ecma-262/#prod-Script">Script</a> global declarations and for top-level declarations within functions.</blockquote><p>And it does not say anything at all about the <em>module Environment Record</em> (except for the example in which the specification helps implementers describe the relationships between the different kinds and types of the <em>Environment Record</em>).</p><p>So why am I so actively using the word “type”?</p><p>In fact, only to link specific types of the <em>Environment Record</em> with the corresponding types of the <em>Lexical Environment</em>.</p><p>When a <em>function Environment </em>is created, its <em>Environment Record</em> is the <em>function Environment Record</em>. Moreover, this <em>function Environment Record</em> is also the <em>declarative Environment Record</em>. That’s why I say that <em>declarative</em> is the kind, and <em>function</em> is the type of the created <em>Environment Record</em>.</p><p>The situation with the <em>module Environment</em> is absolutely analogous. When a <em>module Environment</em> is created, then its <em>Environment Record</em> simultaneously becoms the <em>module Environment Record</em> and the <em>declarative Environment Record</em>. That’s why I say that <em>declarative</em> is the kind, and <em>function</em> is the type of the created <em>Environment Record</em>.</p><p>However, when a <em>global Environment</em> is created, then its <em>Environment Record</em> is the <em>global Environment Record</em>, where the <em>global</em> acts simultaneously as the type and as the kind that represents both the <em>declarative</em> and <em>object</em> kinds simultaneously.</p><p><em>We’ll talk about the function, module and global types in the relevant sections of this chapter.</em></p><p>Therefore, by introducing the term “type” I, in fact, just want to emphasize that it is wrong to think about, for example, the <em>function Environment Record</em> as a subtype of the <em>declarative Environment Record</em>. When a <em>Lexical Environment</em> for a function is created, then such a <em>Lexical Environment</em> is just the “ordinary” <em>Lexical Environment</em>, and the <em>function</em> type is obtained only because its <em>Environment Record</em> is the <em>function Environment Record</em>.</p><p>In other words, when a new <em>Lexical Environment</em> for a function is created, a new <em>declarative Environment Record</em> is created as well for the <em>Lexical Environment</em>. And since the <em>Lexical Environment</em> is created for the function, then its <em>declarative Environment Record</em> is also the <em>function Environment Record</em>. And precisely because the <em>Environment Record</em> of the <em>Lexical Environment</em> is the <em>function Environment Record</em>, the <em>Lexical Environment</em> is also called the <em>function Environment</em>. The situation with the <em>module Environment</em> is similar.</p><p>However, do not think about the <em>global Environment</em> the same way. The <em>global Environment</em> is not <em>global</em> only because its <em>Environment Record</em> is the <em>global Environment Record</em>. Do not forget that the <em>reference to an outer Lexical Environment</em> of the <em>global Environment</em> is <em>null</em>, which is also the reason of why the <em>global Environment</em> is named <em>global</em>.</p><p>The best option is to simply remember the possible combinations of the kinds and the types:</p><ol><li>The <em>Environment Record</em> of the <em>function Environment</em> is always <em>declarative</em> (as the kind) and <em>function</em> (as the type).</li><li>The <em>Environment Record</em> of the <em>module Environment</em> is always <em>declarative</em> (as the kind) and <em>module</em> (as the type).</li><li>The <em>Environment Record</em> of the <em>global Environment</em> is always <em>global</em> (as the kind) (i.e. consists simoultanuosly of <em>declarative</em> and <em>object</em> components) and <em>global</em> (as the type).</li><li>The <em>Environment Record</em> of the “ordinary” <em>Lexical Environment</em> is always either <em>declarative</em> or <em>object</em> (as the kind) and has no type.</li></ol><p>But anyway, why to divide the <em>declarative</em> and <em>object</em> kinds apart from the <em>function</em>, <em>module</em> and <em>global</em> types?</p><p>The answer to this question is that the <strong>kinds</strong> of the <em>Environment Record</em> represent a way of recording (storing) a data, i.e. with what the bindings of the corresponding <em>Lexical Environment</em> are associated, and <strong>types</strong> determine the features of a particular <em>Environment Record</em>.</p><h4><a href="#9605">Declarative Environment Record vs. object Environment Record</a></h4><blockquote>…the <strong>kinds</strong> of <em>Environment Records</em> represent a way of recording (storing) a data, i.e. with what the bindings of the corresponding <em>Lexical Environment</em> are associated…</blockquote><p>Let’s see what the specification says about the <em>declarative Environment Record:</em></p><blockquote>Declarative Environment Records are used to define the effect of ECMAScript language syntactic elements such as <a href="http://www.ecma-international.org/ecma-262/#prod-FunctionDeclaration">FunctionDeclaration</a>s, <a href="http://www.ecma-international.org/ecma-262/#prod-VariableDeclaration">VariableDeclaration</a>s, and <a href="http://www.ecma-international.org/ecma-262/#prod-Catch">Catch</a> clauses that directly associate identifier bindings with ECMAScript language values.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*vJ1zCMDvaFj0UyQPVGmvwA.png" /><figcaption>Figure 24 — The declarative Environment Record card on the <a href="https://www.plectica.com/maps/C7Z4HYSNU">Map</a></figcaption></figure><p>That is, the <a href="http://www.ecma-international.org/ecma-262/#sec-declarative-environment-records"><em>declarative Environment Record</em></a> associates a name with a value. And with nothing more:</p><pre>// example 23. JavaScript</pre><pre>function foo() {</pre><pre>   let a = 1;<br>   console.log(a);</pre><pre>}</pre><p>We can not access the variable a that is stored in the <em>declarative Environment Record</em> of the foo function any other way, except by its name. The value of a is not associated with anything other than the variable a itself.</p><p>And now the <a href="http://www.ecma-international.org/ecma-262/#sec-object-environment-records"><em>object Environment Record</em></a>:</p><blockquote>Object Environment Records are used to define the effect of ECMAScript elements such as <a href="http://www.ecma-international.org/ecma-262/#prod-WithStatement">WithStatement</a> that associate identifier bindings with the properties of some object.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*eglFY4L0Mg3OjlxHjF897Q.png" /><figcaption>Figure 25 — The object Environment Record card on the <a href="https://www.plectica.com/maps/C7Z4HYSNU">Map</a></figcaption></figure><p>Unlike the <em>declarative Environment Record</em>, the <em>object Environment Record</em> associates bindings with object’s properties. As an example, the specification gives us the with statement. Let’s look at it in more detail:</p><pre>// example 24. JavaScript</pre><pre>let o = {a: 1};</pre><pre>with (o) {</pre><pre>    console.log(a);<br>}</pre><p>When the control is transferred to the with block, the current <em>Lexical Environment</em> record for the <em>Running Execution Context</em> is substituted with a new <em>Lexical Environment </em>for its execution. The new <em>Lexical Environment</em> is being created, along with which a new <em>Environment Record</em> of this <em>Lexical Environment</em> is also created.</p><p>Since the with block is neither a function, nor a module, nor a separate script, the <em>Lexical Environment</em> created for it is the “ordinary” <em>Lexical Environment</em>. Let’s turn to the list of the possible combinations of <em>Lexical Environments</em> and <em>Environment Records</em>:</p><blockquote>4. The <em>Environment Reocrd </em>of the “ordinary” <em>Lexical Environment</em> is always either <em>declarative</em> or <em>object</em> (as the kind) and has no type.</blockquote><p>Hence, in the case of the example 24, the ordinary <em>Environment Record</em> is created that does not have any type (that is, with an ordinary, not extended functionality). But at the same time we’re provided with the fact that the created <em>Environment Record</em> is the <em>object Environment Record</em>.</p><blockquote>Unlike the <em>declarative Environment Record</em>, the <em>object Environment Record</em> associates bindings with object’s properties.</blockquote><p>That is why we can access the binding a inside the with statement, and get not the ReferenceError error message, but the value of this variable a, i.e. the a property of the <em>binding object</em> of the <em>Environment Record</em>. <em>Binding object</em> of the <em>Environment Record</em>? Right:</p><blockquote>Each object <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> is associated with an object called its <em>binding object</em>.</blockquote><p>In the example 24, the o object is the <em>binding object</em> of the <em>object Environment Record</em>, associated with the with statement.</p><blockquote>An object <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> binds the set of string identifier names that directly correspond to the property names of its binding object.</blockquote><p>This is what the with statement did. It associated the identifier a with the a property of the object o.</p><blockquote>Property keys that are not strings in the form of an <a href="http://www.ecma-international.org/ecma-262/#prod-IdentifierName">IdentifierName</a> are not included in the set of bound identifiers.</blockquote><p>If the property of the object is named as a variable (identifier) can not be named, then the binding will not be created:</p><pre>// example 25. JavaScript</pre><pre>let o = {&quot;name with spaces&quot;: 1};</pre><pre>with (o) {</pre><pre>    // console.log(name with spaces); ? -&gt; SyntaxError<br>}</pre><p>And this is quite logical, especially considering that variables (or functions) with such “incorrect” identifiers can not even be accessed normally, as it is, for instance, in the example 25.</p><blockquote>Object Environment Records created for with statements (<a href="http://www.ecma-international.org/ecma-262/#sec-with-statement">13.11</a>) can provide their binding object as an implicit this value for use in function calls.</blockquote><p>Implementations are allowed to associate the value of this identifier with the <em>binding object</em>. Therefore, in those implementations in which this is implemented, the following code can be successfully executed:</p><pre>// example 26. JavaScript</pre><pre>let o = {&quot;name with spaces&quot;: 1};</pre><pre>with (o) {</pre><pre>    console.log(this[&quot;name with spaces&quot;]); // 1<br>}</pre><blockquote>The capability is controlled by a withEnvironment Boolean value that is associated with each object <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a>. By default, the value of withEnvironment is false for any object <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a>.</blockquote><p>Each created <em>object Environment Record</em> has the internal record (intrinsic) <em>withEnvironment</em>, which, if it is <em>true</em>, makes it possible to determine whether the <em>Environment Record</em> was created with the help of the with statement, so that an implementation could provide a value for this binding.</p><p>By the way, I already mentioned the importance for us of the <em>Environment Records’</em> intrinsics:</p><blockquote>However, unlike the <em>Agent Records</em>, <em>Environment Record</em>’s intrinsics play a much bigger role for us than the intrinsics of the <em>Agent</em>. But why I say so, we’ll see later.</blockquote><p>Of course, this is not the only important for us intrinsic. We will get acquainted with some others more closely during the consideration of this chapter.</p><p>Now I suggest to discuss in more detail the <em>global Environment Record</em> type of <em>Environment Records</em>, since as we already know, it is represented simultaneously by both the <em>declarative</em> and <em>object</em> kinds, which means that we’ll be able to talk in more detail about the <em>global Environment Record</em> itself as the type, and about the <em>declarative</em> and <em>object</em> kinds of the <em>Environment Record</em> in general.</p><h4><a href="#df57">Global Environment Record</a></h4><p>As you already know, the <em>global Environment Record</em> is an encapsulation of the <em>declarative Environment Record </em>and the <em>object Environment Record</em> (in other words, it is represented by the simulated <em>global Environment Record</em> kind):</p><blockquote>A global <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> is logically a single record but it is specified as a composite encapsulating an object <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> and a declarative <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a>.</blockquote><p>But why should the <em>global Environment Record</em> as a type be represented at the same time as the <em>declarative Environment Record </em>and the <em>object Environment Record</em>? Let’s start with <em>object</em> component.</p><h4><a href="#eb10">Object Component of the global Environment Record</a></h4><blockquote>The object <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> has as its base object the <a href="http://www.ecma-international.org/ecma-262/#global-object">global object</a> of the associated <a href="http://www.ecma-international.org/ecma-262/#realm-record">Realm Record</a>.</blockquote><p>Probably, it would be better if the specification instead of “base object” said the “binding object” (see above).</p><p>From the “Realm<em>”</em> chapter, we already know that when creating a <em>Realm</em>, a <em>global object</em> is also created and is associated with the <em>Realm</em>.</p><h4><a href="#229e">Global object</a></h4><p>In fact, everything is quite simple here: the <a href="http://www.ecma-international.org/ecma-262/#sec-global-object"><em>global object</em></a> is the object that is returned when this is accessed in the global scope:</p><pre>// example 27. JavaScript</pre><pre>// global scope</pre><pre>console.log(this);</pre><p>The output of this code depends on the environment in which you execute it, because, as the specification says:</p><blockquote>In addition to the properties defined in this specification the <a href="http://www.ecma-international.org/ecma-262/#global-object">global object</a> may have additional host defined properties.</blockquote><p>Among other things, there can also be a property that is a reference to the same <em>global object</em> among these host defined properties:</p><blockquote>This may include a property whose value is the <a href="http://www.ecma-international.org/ecma-262/#global-object">global object</a> itself;</blockquote><p>The glaring demonstration of this (which, by the way, is given by the specification) is the <em>global object</em>’s window property (of course, the following example will work as expected only if it is running in a browser):</p><pre>// example 28. JavaScript</pre><pre>console.log(this === this.window);<br>console.log(this === window);<br>console.log(this.window === window);</pre><p>All the calls from the example above should output true, because this points to the <em>global object</em> and its window property points to the same <em>global object</em>.</p><p>And we can access the window as the variable (and not as the property of the this object), because the <em>global object</em> is related to the <em>object</em> component of the <em>global Environment Record</em>. And, as you remember, the <em>global Environment Record</em> associates the identifiers with its <em>binding object</em>’s properties:</p><blockquote>Unlike the <em>declarative Environment Record</em>, the <em>object Environment Record</em> associates bindings with object’s properties.</blockquote><p>In the case of the example 28, the identifier becomes window, and its value becomes the value of the window property of the this object.</p><p>But why does the <em>global Environment Record</em> have the this binding at all?</p><h4><a href="#772a">This and intrinsics</a></h4><p>I have repeatedly said about the importance of <em>Environment Record</em>’s intrinsics:</p><blockquote>However, unlike the <em>Agent Records</em>, <em>Environment Record</em>’s intrinsics play a much bigger role for us than the intrinsics of the <em>Agent</em>. But why I say so, we’ll see later.</blockquote><p>The fact is that it is the intrinsics of a particular <em>Environment Record</em> which determine its differences from the other <em>Environment Records</em> (in other words, determine its <strong>type</strong>).</p><p>One of such important intrinsics directly for the <em>global Environment Record</em> is the <em>[[GlobalThisValue]]</em>:</p><blockquote><em>[Composite]</em></blockquote><blockquote>[[GlobalThisValue]] — The value returned by <strong>this</strong> in global scope. Hosts may provide any ECMAScript Object value.</blockquote><p>When we refer to this in the code of the <em>global Environment</em>, the implementation performs the abstract operation <em>GetThisBinding</em>:</p><blockquote>This <a href="http://www.ecma-international.org/ecma-262/#global-object">global object</a> is the value returned by the global <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a>’s GetThisBinding concrete method.</blockquote><p><em>Do not you get confused, please. I call the method “abstract”, because it is abstract for us. The specification calls it “concrete” because any implementation has a very specific implementation (realization) of this method and because it (or rather it’s algorithm) is concrete from the specification’s point of view.</em></p><p>The <em>GetThisBinding</em> method itself is defined in the <a href="http://www.ecma-international.org/ecma-262/#sec-global-environment-records-getthisbinding">8.1.1.4.11</a> clause of the specification as follows:</p><blockquote>1. Let envRec be the global <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> for which the method was invoked.</blockquote><blockquote>2. Return envRec.[[GlobalThisValue]].</blockquote><p>It immediately becomes clear from this algorithm that the current value associated with this is stored in some form directly in the <em>[[GlobalThisValue]]</em> intrinsic itself, and the method is needed to manipulate with this intrinsic (its value).</p><p>This is also true in general case. Intrinsics (they are differently called “additional fields” in the specification) store directly some values, and methods just manipulate with these values, referring to their receipt to the intrinsics themselves.</p><p>There is still a quite large number of other methods and a relatively small number of intrinsics specific for the <em>global Environment Record</em>. All of them can be found in Tables <a href="http://www.ecma-international.org/ecma-262/#table-18">17</a> and <a href="http://www.ecma-international.org/ecma-262/#table-19">18</a> of the specification respectively.</p><p>Derictly the intrinsics and methods (the methods can also be treated as intrinsics from our point of view) specific for a particular <em>Environment Record</em> are the ones that determine its type.</p><p>To execute the code of the global scope, a new <em>Lexical Environment</em> is created. As I said earlier, initially this <em>Lexical Environment</em> is the “ordinary” <em>Lexical Environment</em> (if we do not take into account that it does not have the <em>reference to an outer Lexical Environment</em>, or rather that its value is <em>null</em>). In this case, when the <em>Lexical Environment</em> is created, an <em>Environment Record</em> is also created for it. So, due to the fact that it is the global scope code that is being executed, the created <em>Environment Record</em> receives certain intrinsics peculiar only to the <em>Environment Record</em> associated with the global scope code. It is thanks to these specific intrinsics that extend the functionality of this <em>Environment Record</em> that this <em>Environment Record</em> is called the <em>global Environment Record</em>. This proves once again that the <em>global Environment Record</em> is exactly the <strong>type</strong> of the <em>Environment Record</em> (although is the kind simultaneously, as it is said a hundred times before).</p><p>But still, why in the chapter on the <em>Lexical Environments</em> I said that the presence of this is a feature of precisely of the <em>function</em> type of the <em>Lexical Environment</em> (in fact, the <em>function Environment Record</em>, as you’ll learn soon), although, as we just learned, the <em>global Environment</em> (the <em>global Environment Record</em>) do also provide us with the this binding?</p><p>In fact, the reason is covered under <strong>how</strong> I presented the value of this.</p><p>When we talked about the <em>function Environment</em>, I said that this is the only ECMAScript value that is dynamically scoped:</p><blockquote>Nevertheless, the ECMAScript defines one (and the only one) “variable”, the value of which is scoped dynamically. And such a variable is this.</blockquote><p>The truth is that the <em>function Environment Record</em> scopes this dynamically for fair. However, I didn’t specify thereat that this is scoped dynamically <strong>exclusively</strong> in <em>function Environment Records</em>.</p><p>And for real, it is quite logical to say that the <em>global Environment Record</em> scopes this statically!</p><p>First, this is the value provided by the <em>object</em> component of the <em>global Environment Record</em>. And the <em>object</em> component, in turn, is represented by the <em>global object</em>.</p><p>But, as written in the specification in the chapter on the <em>global object</em> itself, the <em>global object</em> does not have the internal <em>[[Call]]</em> and <em>[[Construct]]</em> methods:</p><blockquote>The <a href="http://www.ecma-international.org/ecma-262/#global-object">global object</a> does not have a [[Construct]] internal method; it is not possible to use the <a href="http://www.ecma-international.org/ecma-262/#global-object">global object</a> as a constructor with the <strong>new</strong> operator.</blockquote><blockquote>The <a href="http://www.ecma-international.org/ecma-262/#global-object">global object</a> does not have a [[Call]] internal method; it is not possible to invoke the <a href="http://www.ecma-international.org/ecma-262/#global-object">global object</a> as a function.</blockquote><p>Simply put, the <em>global object</em> can not be called neither as a function nor as a constructor. And when we talked about the <em>function Environent</em>, I explicitly clarified that this value inside the function associated with the relevant <em>function Environment</em> is determined exactly by how the function is called.</p><p>Therefore, since the <em>global object</em> can not be called at all, this value of the <em>global Environment Record</em> must be defined somehow differently. And yes, it is. By the way, I already spoke about this in this section, let me remind you:</p><blockquote>This <a href="http://www.ecma-international.org/ecma-262/#global-object">global object</a> is the value returned by the global <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a>’s GetThisBinding concrete method.</blockquote><p>In other words:</p><blockquote><em>[Not from the specification]</em></blockquote><blockquote>This <a href="http://www.ecma-international.org/ecma-262/#global-object">global object</a> is the value returned by the global <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a>’s this binding.</blockquote><p>That is, the this binding is created immediately when creating the <em>global Environment Record</em>, along with it. Also, along with the <em>global Environment Record</em>, the <em>global object</em> is also created. When the <em>global object</em> is created, then the value of the this binding is associated with the <em>global object</em> itself.</p><p>Therefore, this, when used inside the <em>global Environment</em> (i.e. global scope), can be thought of as an ordinary variable, same as we ourselves can define using the var keyword. The only thing is that its value is determined by implementations, long before we can define at least some other variable. Namely, along with the very creation of the <em>global Environment Record</em> itself.</p><p>Thus, the value of this is not scoped in the <em>global Environment</em> dynamically, but is rather scoped statically.</p><h4><a href="#38ee">Preinitialized properties of the global object</a></h4><blockquote>A <a href="http://www.ecma-international.org/ecma-262/#global-environment">global environment</a>’s EnvironmentRecord may be prepopulated with identifier bindings and includes an associated global object whose properties provide some of the <a href="http://www.ecma-international.org/ecma-262/#global-environment">global environment</a>’s identifier bindings. As ECMAScript code is executed, additional properties may be added to the <a href="http://www.ecma-international.org/ecma-262/#global-object">global object</a> and the initial properties may be modified.</blockquote><p>On a closer examination of this part…</p><blockquote>A <a href="http://www.ecma-international.org/ecma-262/#global-environment">global environment</a>’s EnvironmentRecord may be prepopulated with identifier bindings and includes an associated global object whose properties provide some of the <a href="http://www.ecma-international.org/ecma-262/#global-environment">global environment</a>’s identifier bindings.</blockquote><p>…it’s seen that it’s a vicious circle.</p><p>The <em>global Environment Record</em> is associated with the <em>global object</em>. Or rather, the <em>object</em> component of the <em>global Environment Record</em> is represented by the <em>global object</em>:</p><blockquote>The object <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> has as its base object the <a href="http://www.ecma-international.org/ecma-262/#global-object">global object</a> of the associated <a href="http://www.ecma-international.org/ecma-262/#realm-record">Realm Record</a>.</blockquote><p>At the same time, the <em>global Environment Record</em> can initially contain some bindings:</p><blockquote>A <a href="http://www.ecma-international.org/ecma-262/#global-environment">global environment</a>’s EnvironmentRecord may be prepopulated with identifier bindings…</blockquote><p>But, it turns out from the quote that this <em>global object</em> itself is the one that contains these preinitialized (predefined) bindings, doesn’t it?</p><blockquote>…global object whose properties provide some of the <a href="http://www.ecma-international.org/ecma-262/#global-environment">global environment</a>’s identifier bindings.</blockquote><p>Absolutely right. By the way, I’ve already made a brief mention of this, when we were just beginning to consider the <em>global object</em> itself:</p><blockquote>In addition to the properties defined in this specification the <a href="http://www.ecma-international.org/ecma-262/#global-object">global object</a> may have additional host defined properties.</blockquote><p>So what are these predefined properties? As can be seen from the quote above, there are 2 types of such properties: host defined and defined by the specification.</p><p>It is clear that specific host defined properties are determined solely by implementations. One of these properties is the previously discussed window property.</p><p>But what properties are defined by the specification as mandatory?</p><p>There are only 14 such properties (<a href="http://www.ecma-international.org/ecma-262/#sec-value-properties-of-the-global-object">18.1</a>, <a href="http://www.ecma-international.org/ecma-262/#sec-function-properties-of-the-global-object">18.2</a>). And there’re only 3 precisely <strong>properties</strong> but not the methods: Infinity, NaN and undefined.</p><p>It is easy to calculate that there’re 11 methods. Of course, we will not talk about all of them. Instead, I suggest to consider all the <strong>properties</strong> (because there are not too many of them), and eval as a representative of all the <strong>methods</strong>.</p><p>Infinity and NaN are references to the relevant properties of the Number constructor:</p><pre>// example 29. JavaScript</pre><pre>console.log(Infinity === Number.POSITIVE_INFINITY); // true<br>// console.log(NaN === Number.NaN);</pre><p>NaN and Number.NaN are absolutely the same and there is absolutely no difference in what to use. I commented out the last line in the example above, because NaN is never equal to itself. The explanation of why this is so is, obviously, beyond the scope of this article. It is important for you only to understand that NaN is the reference to Number.NaN.</p><p>But why do we need predefined properties?</p><p>Obviously, Infinity and NaN are predefined for convenience. Instead of writing Number.POSITIVE_INFINITY and Number.NaN each time, you can simply refer to the Infinity and NaN global properties respectively, which is much shorter.</p><p>But wait, if we have, for example, the following code:</p><pre>// example 30. JavaScript</pre><pre>function foo() {</pre><pre>    function bar() {<br>        function baz() {<br>            console.log(NaN);</pre><pre>        }</pre><pre>    }<br>}</pre><p>Then would it not be more reasonable in terms of perfomance, to refer directly to Number.NaN, instead of going up all the chain of <em>references to an outer Lexical Environment</em>, until we get to the <em>global Environment Record</em>, the reference to the value of NaN is stored in the <em>global object</em> of which?</p><p>No. For two reasons:</p><ol><li>First of all, as we already know, the reference to the <em>global object</em> is stored in the <em>[[GlobalObject]]</em> intrinsic of the <em>Realm Record</em>. Therefore, there is no need to go up all the chain of <em>references to an outer Lexical Environment</em> to the <em>global Environment </em>itself in order to get the NaN&#39;s value from the <em>object</em> component of the <em>global Environment Record</em> of which.</li><li>Secondly, objects like Number are predefined themselves. But more on that later.</li></ol><p>As for undefined and eval, then you can’t reach them from nowhere else at all. The values represented by these bindings are associated, unlike Infinity and NaN, only with the properties of the <em>global object</em> of the same names. Therefore, each time when accessing the undefined or eval, an implementation refers to the <em>global object</em> (the reference to which, as we recall, is stored in the <em>Realm</em> record of the <em>Running Execution Context</em>):</p><pre>// example 31. JavaScript</pre><pre>console.log(this.undefined === undefined); // true<br>console.log(this.eval === eval); // true</pre><p>Even though the specification says that the predefined properties can be changed (modified):</p><blockquote>As ECMAScript code is executed, additional properties may be added to the <a href="http://www.ecma-international.org/ecma-262/#global-object">global object</a> and the initial properties may be modified.</blockquote><p>…this does not apply to the predefined properties described by the specification as mandatory because the values of the writable and configurable descriptors of all of these properties are set to false (<a href="http://www.ecma-international.org/ecma-262/#sec-value-properties-of-the-global-object">18.1</a>).</p><pre>// example 32. JavaScript</pre><pre>undefined = 1;<br>console.log(undefined); // undefined</pre><pre>Infinity = 1;<br>console.log(Infinity); // Infinity</pre><pre>NaN = 1;<br>console.log(NaN); // NaN</pre><p>However, before the existence of property descriptors (before they became defined by the specification), the possibility of redefinition existed for them. In particular, you could assign a new value to the undefined. By the way, it’s most likely that the existance of the void operator is a consequence of this.</p><p>As for the Infinity and NaN, honestley, I don’t know. I did not check it at the right time, and now there is neither opportunity nor need.</p><blockquote>…because the values of the writable and configurable descriptors of all of these properties are set to false (<a href="http://www.ecma-international.org/ecma-262/#sec-value-properties-of-the-global-object">18.1</a>).</blockquote><p>Actually, not of the all of them. The specification does not say a word about the descriptors of the eval method (nor any other methods). And it is for the reason that eval actually can be redefined:</p><pre>// example 33. JavaScript</pre><pre>eval = function() {</pre><pre>    console.log(&quot;Eval is Evil!&quot;);<br>}</pre><pre>eval(); // &quot;Eval is Evil!&quot;</pre><p>The ability to override host defined properties of the <em>global object</em> is determined solely by implementations (obviously because they give them certain descriptors themselves).</p><blockquote>Secondly, objects like Number are predefined themselves. But more on that later.</blockquote><p>And indeed it is:</p><blockquote>A global <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> provides the bindings for built-in globals…</blockquote><p>Such built-in globals is a very large number of objects: Object, Function, Number, String, Error, RegExp and many more. There’re 10 chapters devoted to them in the Specification (from the 17th to the 26th)!</p><p>It’s clear that we will not talk about them separately, because this is beyond the scope of this article.</p><p>By the way, one of these built-in global objects is the <em>global object</em> itself:</p><blockquote>One, the <a href="http://www.ecma-international.org/ecma-262/#global-object">global object</a>, is part of the lexical environment of the executing program.</blockquote><p>Which, as we already know (and as the specification recalls), is the part of the <em>Lexical Environment</em> (or rather of the <em>global Environment Record</em>) of the <em>Execution Context</em> in which the script is executed.</p><blockquote>Others are accessible as initial properties of the <a href="http://www.ecma-international.org/ecma-262/#global-object">global object</a> or indirectly as properties of accessible built-in objects.</blockquote><p>That’s why I said that the objects like Number are predefined. That is, such objects are available as properties of the <em>global object</em>:</p><pre>// example 34. JavaScript</pre><pre>console.log(this.Number === Number); // true<br>console.log(this.String === String); // true<br>console.log(this.Error === Error); // true</pre><p>And, perhaps not directly, but rather as properties of these objects themselves (for example, from a prototype):</p><pre>// example 35. JavaScript</pre><pre>console.log(Number.prototype.constructor === Number); // true<br>console.log(String.prototype.constructor === String); // true<br>console.log(Error.prototype.constructor === Error); // true</pre><h4><a href="#b218">Runtime-defined properties of the global object</a></h4><blockquote>The object <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> component of a global <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> contains the bindings for all built-in globals (clause <a href="http://www.ecma-international.org/ecma-262/#sec-global-object">18</a>) and all bindings introduced by a <a href="http://www.ecma-international.org/ecma-262/#prod-FunctionDeclaration">FunctionDeclaration</a>, <a href="http://www.ecma-international.org/ecma-262/#prod-GeneratorDeclaration">GeneratorDeclaration</a>, <a href="http://www.ecma-international.org/ecma-262/#prod-AsyncFunctionDeclaration">AsyncFunctionDeclaration</a> or <a href="http://www.ecma-international.org/ecma-262/#prod-VariableStatement">VariableStatement</a> contained in global code.</blockquote><p>In addition to the already discussed predefined properties, the <em>global Environment Record</em> can also contain runtime-defined properties.</p><p>As we remember, the <em>global Environment Record</em> is presented by both the <em>object</em> and <em>declarative</em> components. At the same time, the <em>object</em> component is represented by the <em>global object</em>. Therefore, it is quite simple to define a new property for the <em>object </em>component of the <em>global Environment Record</em>:</p><pre>// example 36. JavaScript</pre><pre>this.a = 1;<br>window.b = 1; // remember that window is the global object only in HTML DOM (i.e. in browsers)</pre><p>And, since the <em>object Environment Record</em> associates bindings with the properties of its <em>binding object</em>, it is possible to address the properties of the <em>global object</em> which are defined in the example 36 simply refering to their identifiers:</p><pre>// example 37. JavaScript</pre><pre>console.log(a);<br>console.log(b);</pre><p>In addition, as can be seen from the definition, all the declarations of functions, generators, asynchronous functions and variables declared with the var keyword are also included in the <em>object</em> component of the <em>global Environment Record</em>.</p><p>That’s why I once compared this to a variable declared with the var keyword:</p><blockquote>Therefore, this, when used inside the <em>global Environment</em> (i.e. global scope), can be thought of as an ordinary variable, same as we ourselves can define using the var keyword. The only thing is that its value is determined by implementations, long before we can define at least some other variable. Namely, along with the very creation of the <em>global Environment Record</em> itself.</blockquote><p>That is because this points to the <em>global object</em> (which is the <em>binding object</em> of the <em>global Environment Record</em>’s <em>object</em> component), and variables that will also belong to the <em>global Environment Record</em>’s <em>object</em> component after declaration can only be declared using the var keyword.</p><pre>// example 38. JavaScript</pre><pre>function foo() {}<br>console.log(foo === this.foo); // true</pre><pre>async function bar() {}<br>console.log(bar === this.bar); // true</pre><pre>function* baz() {}<br>console.log(baz === this.baz); // true</pre><pre>var a = 1;<br>console.log(a === this.a); // true</pre><blockquote>As ECMAScript code is executed, additional properties may be added to the <a href="http://www.ecma-international.org/ecma-262/#global-object">global object</a> and the initial properties may be modified.</blockquote><p>As we already know, not all properties of the <em>global object</em> can be modified. However, all the bindings that are dynamically added to the <em>object</em> component of the <em>global Environment Record</em> can:</p><pre>// example 39. JavaScript</pre><pre>function foo() {}<br>foo = 1;<br>console.log(foo); // 1</pre><pre>var a = 1;<br>a = 2;<br>console.log(a); // 2</pre><blockquote>Because properties can be dynamically added and deleted from objects, the set of identifiers bound by an object <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> may potentially change as a side-effect of any operation that adds or deletes properties.</blockquote><p>An example of dynamic creation, and then dynamic removal of a binding:</p><pre>// example 40. JavaScript</pre><pre>this.a = 1;<br>console.log(a); // 1</pre><pre>delete a;<br>console.log(a); // ReferenceError</pre><p>At the same time, such binding, implicitly created after defining the property of the <em>global object</em>, is mutable even if the writable attribute of this property is set to false:</p><blockquote>Any bindings that are created as a result of such a side-effect are considered to be a mutable binding even if the Writable attribute of the corresponding property has the value false. Immutable bindings do not exist for object Environment Records.</blockquote><pre>// example 41. JavaScript</pre><pre>Object.defineProperty(this, “prop”, {<br> value: 1,<br> writable: false<br>});</pre><pre>console.log(prop); // 1</pre><pre>this.prop = 2; // forbidden because the writable property descriptor is set to false<br>console.log(prop); // 1</pre><pre>prop = 3; // must work! But...<br>console.log(prop); // must be 3</pre><p>If you run this example, you’ll see that the output of the last line is 1! But this is a complete nonsense, you may say, especially taking into account the written in the specification:</p><blockquote>Immutable bindings do not exist for object Environment Records.</blockquote><p>That is, immutable <strong>properties</strong> of an object can exist. But if the object is the <em>object Environment Record</em>’s <em>binding object</em>, then when the value of the corresponding <strong>binding</strong> changes, the value of the property itself must change too, even if it is immutable.</p><p>But this does not happen for some reason. Why?</p><p>In fact, it’s all a matter of not exact wording. <a href="https://github.com/littledan">Daniel Ehrenberg</a> (the owner of the specification’s repository on GitHub) have grately honored me by <a href="https://github.com/tc39/ecma262/issues/1084#issuecomment-361134309">spelling out</a> what is written in the specification.</p><p>The writable descriptor determines whether the property value can be changed using the assignment operator. However, as Daniel said:</p><blockquote>No, just because the binding itself isn’t considered “immutable” in this particular piece of technical language doesn’t mean you can necessarily change it.</blockquote><p>In other words, the word “mutable” in this particular quote from the specification is not an antonym to the word “immutable”. The word “immutable” is a special term used by the specification to refer to bindings, such as those declared with the const keyword. Deneil stressed this separately as well:</p><blockquote>“immutable binding” is a specific term used in environment records to refer to certain kinds of bindings, such as that created by const declarations.</blockquote><p>However, since many of the editors of the specification are also the implementators of specific ECMAScript implementations, everything is implemented by them exactly as intended by these editors themselves. But it’s just not described the proper way in the specification.</p><p>In any case, Deniel agreed that such a formulation is incorrect and invited the other contributor to correct it. Therefore, most likely, that in the next version of the specification you will not be able anymore to find this quote in the form in which it exists now.</p><p>And the last thing I would like to mention considering the <em>global object</em>.</p><blockquote>Properties may be created directly on a <a href="http://www.ecma-international.org/ecma-262/#global-object">global object</a>. Hence, the object <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> component of a global <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> may contain both bindings created explicitly by <a href="http://www.ecma-international.org/ecma-262/#prod-FunctionDeclaration">FunctionDeclaration</a>, <a href="http://www.ecma-international.org/ecma-262/#prod-GeneratorDeclaration">GeneratorDeclaration</a>, <a href="http://www.ecma-international.org/ecma-262/#prod-AsyncFunctionDeclaration">AsyncFunctionDeclaration</a>, or <a href="http://www.ecma-international.org/ecma-262/#prod-VariableDeclaration">VariableDeclaration</a> declarations and bindings created implicitly as properties of the <a href="http://www.ecma-international.org/ecma-262/#global-object">global object</a>. In order to identify which bindings were explicitly created using declarations, a global <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> maintains a list of the names bound using its CreateGlobalVarBinding and CreateGlobalFunctionBinding concrete methods.</blockquote><p>Such a list is stored in yet another important intrinsic of the <em>global Environmental Record</em> — the <em>[[VarNames]]</em> one:</p><blockquote><em>[Composite]</em></blockquote><blockquote>[[VarNames]] — The string names bound by <a href="http://www.ecma-international.org/ecma-262/#prod-FunctionDeclaration">FunctionDeclaration</a>, <a href="http://www.ecma-international.org/ecma-262/#prod-GeneratorDeclaration">GeneratorDeclaration</a>, <a href="http://www.ecma-international.org/ecma-262/#prod-AsyncFunctionDeclaration">AsyncFunctionDeclaration</a>, and <a href="http://www.ecma-international.org/ecma-262/#prod-VariableDeclaration">VariableDeclaration</a> declarations in global code for the associated <a href="http://www.ecma-international.org/ecma-262/#realm">realm</a>.</blockquote><p>This list is maintained for the correct functioning of some operators. In particular, the delete operator can delete object’s properties that were declared explicitly as object properties, but can not delete object’s properties that were implicitly defined (using the constructions listed in the qoute above):</p><pre>// example 42. JavaScript</pre><pre>this.a = 1;<br>var b = 2;</pre><pre>delete a;<br>delete b;</pre><pre>console.log(a); // ReferenceError<br>console.log(b); // 2</pre><h4><a href="#4b68">Declarative component of the global Environment Record</a></h4><blockquote>The bindings for all other ECMAScript declarations in global code are contained in the declarative <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> component of the global <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a>.</blockquote><p>All the declaration keywords besides those discussed in the previous section, that is, the let and const, belong to the <em>declarative</em> component of the <em>global Environment Record</em>.</p><pre>// example 43. JavaScript</pre><pre>let a = 1;<br>const b = 2;</pre><pre>console.log(this.a); // undefined<br>console.log(this.b); // undefined</pre><p>Since it is the <em>object</em> component of the <em>global Environment Record</em> which is represented by the <em>global object</em>, variables declared using the let and const keywords do not fall into the <em>global object</em>.</p><p>By the way, about the const keyword. The <em>declarative</em> component of the <em>global Environment Record</em>, in contrast to the <em>object</em> component, may contain immutable bindings (as well as the <em>declarative Environment Record</em> in general). Otherwise, the correct operation of const would be simply impossible.</p><pre>// example 44. JavaScript</pre><pre>const PI = 3.141592653589793;<br>PI = 3.14; // TypeError</pre><h4><a href="#93d0">Function Environment Record</a></h4><blockquote>A function Environment Record is a declarative <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> that is used to represent the top-level scope of a function and, if the function is not an <a href="http://www.ecma-international.org/ecma-262/#prod-ArrowFunction">ArrowFunction</a>, provides a this binding.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*B32OQtDngNy53-zlxsdkog.png" /><figcaption>Figure 26 — The function Environment Record card on the <a href="https://www.plectica.com/maps/C7Z4HYSNU">Map</a></figcaption></figure><p>First, as we have already considered before and as the specification reminds us again, the <a href="http://www.ecma-international.org/ecma-262/#sec-function-environment-records"><em>function Environment Record</em></a> is always the <em>declarative Environment Record</em>.</p><p>When we were considering the <em>function Environment</em>, I said:</p><blockquote>As you can see, it is the <em>function Environment</em> who determines the value of the this inside a function.</blockquote><p>Now, speaking of <em>Environment Records</em>, it would be more correct to say that it is not directly the <em>function Environment</em> the one that determines the value of this inside functions, but the <em>function Environment Record</em> of this <em>function Environment</em>. And, as you already know, the <em>function Environment</em> is therefore called the <strong><em>function</em></strong><em> Environment</em>, because its <em>Environment Record</em> is precisely the <strong><em>function</em></strong><em> Environment Record</em>.</p><p>In addition, as can be seen from the afore definition of the <em>function Environment Record</em>, the value for this binding may not be provided at all. The presence of this is determined by the state of the <em>function Environment Record</em>’s <em>[[ThisBindingStatus]]</em> intrinsic.</p><p>This intrinsic can take one of 3 states: “lexical”, “initialized” and “uninitialized”.</p><p>“Uninitialized” is the original state. As soon as an implementation assigns some value to this, the state changes to “initialized”, and the value itself is written directly into the <em>[[ThisValue]]</em> intrinsic.</p><p><em>The [[ThisBindingStatus]]</em> is used by the specification to describe the internal algorithms and by implementations for implementing these algorithms, in order to determine the real state of this. The <em>[[ThisValue]]</em> in turn <strong>directly</strong> reflects the value of this binding.</p><p>In addition to the “initialized” and “uninitialized”, the <em>[[ThisBindingStatus]]</em> intrinsic can also take the “lexical” value:</p><blockquote>If the value is <strong>&quot;lexical&quot;</strong>, this is an <a href="http://www.ecma-international.org/ecma-262/#prod-ArrowFunction">ArrowFunction</a> and does not have a local this value.</blockquote><p>When an arrow function is called, it does not matter at all <strong>how</strong> it was called, because this inside it is scoped lexically (statically):</p><pre>// example 45. JavaScript</pre><pre>function foo() {<br>    let thisOfTheScopeAbove = this;</pre><pre>    let o = {<br>        bar: function() {<br>            console.log(this === thisOfTheScopeAbove); // false<br>        },</pre><pre>        baz: () =&gt; {<br>            console.log(this === thisOfTheScopeAbove); // true<br>        }<br>    }</pre><pre>    o.bar();<br>    o.baz();<br>}</pre><pre>foo();</pre><p>The value of this inside the arrow function is taken from the scope in which the arrow function is defined.</p><blockquote>The fact that the <em>function Environment</em> provides a value for the this binding is only one of the 2 differences between the <em>function Environment</em> and the “ordinary” <em>Lexical Environment</em>.</blockquote><blockquote>The second difference is that the <em>function Environment</em> also includes some stuff that is needed to support the super invokations:</blockquote><p>This is another quote from the previous chapter. Now it is obvious that this is not the <em>function Environment</em> that includes this “stuff”, but the <em>function Environment Record</em> of this <em>function Environment</em>. And this “stuff” is represented by the <em>[[HomeObject]]</em> intrinsic.</p><blockquote><em>[Composite]</em></blockquote><blockquote>[[HomeObject]] — If the associated function has super property accesses and is not an <a href="http://www.ecma-international.org/ecma-262/#prod-ArrowFunction">ArrowFunction</a>, [[HomeObject]] is the object that the function is bound to as a method. The default value for [[HomeObject]] is undefined.</blockquote><p>That is, the <em>[[HomeObject]]</em> intrinsic refers to an object in which a method that refers to the super is defined.</p><p>But wait, then why with the help of the super statement it is possible to get access to the methods (properties) of a <strong>prototype</strong> of the object?</p><pre>// example 46. JavaScript</pre><pre>class Foo {<br>    baq() {<br>        console.log(&quot;Hello!&quot;);<br>    }<br>}</pre><pre>class Bar extends Foo {<br>    baq() {<br>        console.log(&quot;Not me!&quot;);<br>    }</pre><pre>    baz() {<br>        super.baq();<br>    }<br>}</pre><pre>(new Bar).baz();</pre><p>The thing here is that intrinsics in fact only store certain values. Implementations do not directly operate on them, but do so using some methods that in turn access certain intrinsics. This also happens in the case of the <em>[[HomeObject]]</em>.</p><p>When you access the super, the abstract method <a href="http://www.ecma-international.org/ecma-262/#sec-getsuperbase">8.1.1.3.5</a> <em>GetSuperBase</em> is perfomed. The last step of this method is to return the prototype of the object obtained by accessing the <em>[[HomeObject]]</em> intrinsic:</p><blockquote>Return ? home.[[GetPrototypeOf]]().</blockquote><p>That’s why in the example 46 the baq method of the <em>[[HomeObject]]</em>’s prototype is invoked, but not the baq of the <em>[[HomeObject]]</em> itself.</p><p>This can also be demonstrated in a more obvious example:</p><pre>// example 47. JavaScript</pre><pre>var prototype = {<br>    bar() {<br>        console.log(&#39;Hello!&#39;);<br>    }<br>}</pre><pre>var base = {<br>    foo() {<br>        super.bar();<br>    }<br>}</pre><pre>Object.setPrototypeOf(base, prototype);<br>base.foo();</pre><p>In this example, we explicitly set the prototype of the base object to the prototype object. And when accessing bar, it is the bar method of this prototype invoked, which proves once again that when accessing super, it does not return the value of the <em>[[HomeObject]]</em> intrinsic itself, but the prototype of the object to which this intrinsic points.</p><p>Another proof that the support of the super is a distinctive feature of the <strong><em>function</em></strong><em> Environment Record</em> is that the super can not be used in any other <em>Environment Record</em>:</p><pre>// example 48. JavaScript</pre><pre>var prototype = {<br>    bar() {<br>        console.log(&#39;Hello!&#39;);<br>    }<br>}</pre><pre>var base = {<br>    foo: super.bar<br>}</pre><pre>Object.setPrototypeOf(base, prototype);<br>base.foo();</pre><p>In this example, the super keyword does not refer to the <em>function Environment</em>, but to the <em>global Environment</em> (because a new <em>Lexical Environment</em> is not created for the object definition, don’t mix up with a block definition). Since the abstract method <em>GetSuperBase</em> is not defined for the <em>global Environment Record</em> (as the <em>[[HomeObject]]</em> instrinsic itself, which this method operates on), such a use of the super will result in a SyntaxError error.</p><h4><a href="#c9ed">Variable Environment</a></h4><p>In the previous chapter we already talked a little about the <em>Variable Environment</em>, and I said thereat that the <em>Variable Environments</em> are used not only for delimiting variables declared using the var keyword from variables declared using the let keyword. Sometimes the <em>Variable Environment</em> is used for other purposes:</p><blockquote>In fact, the <em>Variable Environment</em> is in some cases used by implementations for other purposes. We will talk about one of them in more detail after we get acquainted with <em>Environment Records</em>.</blockquote><p>It seems to me that now is the right time to take a look at a specific example:</p><pre>// example 49. JavaScript</pre><pre>function bar(a, foo = () =&gt; a) {<br>    var a = 2;</pre><pre>    console.log(foo());<br>};</pre><pre>bar(1);</pre><p>How do you think, what is the result of its evaluation? 2? Actually, the output is 1. Let’s sort out why.</p><p>First of all, a new <em>Execution Context</em> is created to execute the function. When it is created, it also leads to creation of 2 <em>Lexical Environments</em>: the <em>Lexical Environment</em> and the V<em>ariable Environment</em>. Initially, they are exactly the same (in fact, the V<em>ariable Environment</em> is an exact double of the <em>Lexical Environment</em>).</p><p>I have never mentioned until now that in fact the evaluation of the function does not begin directly with the execution of its body. Before directly executing the body, an implementation first sorts out the formal parameters of the function and initializes all the declarations inside its body.</p><p>The answer to why the output of the example 49 is 1 is covered precisely in the formal parameters.</p><p>The fact is that if a function declaration has at least one parameter among its formal parameters, for which a default value is provided, then a separate (second, as the specification calls it) <em>Environment Record</em> is created for all the declarations inside the body of the function:</p><blockquote>If default value parameter initializers exist, a second Environment Record is created for the body declarations.</blockquote><p>In fact, this is not entirely true. The phrase “second Environment Record” confused me initially. But don’t think that the <em>Lexical Environment</em> can have 2 <em>Environment Records</em> simultaneously:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*DjcDAd8FvNcqy0S429KhnQ.jpeg" /><figcaption>Figure 27 — One Lexical Environment can not have 2 Environment Records simultaneously!</figcaption></figure><p>You already know that <em>Environment Records</em> do not exist by themselves. They always exist in the context of a certain <em>Lexical Environment</em> (or <em>Variable Environment</em>). Therefore, when the specification says that a second <em>Environment Record</em> is being created, it actually means that a new <em>Lexical Environment</em> (or <em>Variable Environment</em>) is being created, together with which, as we already know, a new <em>Environment Record</em> is being created as well.</p><p>This is exactly what happens in the example 49. If you look at the step “27.b” of the specification’s abstract algorithm <a href="http://www.ecma-international.org/ecma-262/#sec-functiondeclarationinstantiation">9.2.12</a>, you will notice that it is actually the <em>Lexical Environment</em> (rather than the <em>Environment Record</em>) that actually gets created.</p><p>By the way, the fact that the operation that creates the new <em>Lexical Environment</em> is called <em>New</em><strong><em>Declarative</em></strong><em>Environment</em> proves once again that the type of the <em>Lexical Environment</em> is determined by the type of the <em>Environment Record</em> being created for it. In this case the <em>declarative</em><strong><em> </em></strong><em>Environment Record</em> is created.</p><blockquote>If default value parameter initializers exist, a second Environment Record is created for the body declarations.</blockquote><p>In cases where there are no default parameters, the step 26 of the <a href="http://www.ecma-international.org/ecma-262/#sec-functiondeclarationinstantiation">9.2.12</a> algorithm is performed. It’s also explicitly said in it that:</p><blockquote>NOTE: Only a single lexical environment is needed for the parameters and top-level vars.</blockquote><p>This means that if there are no any default parameter initializers among the formal parameters of the function exist, then all the formal parameters and all the top-level declarations in the body of the function (even including var-declarations!) fall into the <strong><em>Lexical</em></strong><em> Environment</em> of the <em>Running Execution Context</em>, and the <em>Variable Environment</em> in this case remains unaffected.</p><p>But after all, in the step “27.b” the <strong><em>Variable</em></strong><em> Environment</em> is created, not the <em>Lexical Environment.</em> Then why did I say that the <em>Variable Environment</em> of the <em>Running Execution Context</em> remains unaffected? Is it somehow used when the default parameters are present?</p><p>Yes. The fact is that, as I have repeatedly mentioned before, both <em>Lexical Environment</em> and <em>Variable Environment</em> are the <em>Lexical Environments</em>. And in the step “27.d”, the <em>Lexical Environment</em> created for declarations inside the body of the function replaces the existing <em>Variable Environment</em> record of the <em>Running Execution Context</em>, that is, it becomes the <strong><em>Variable</em></strong><em> Environment</em> itself. At the same time, its <em>reference to an outer Lexical Environment</em> points to the <strong><em>Lexical</em></strong><em> Environment</em> of <strong>the same</strong> <em>Running Execution Context</em> (this is necessary so that other functions that are defined inside the body of the function could have access to both formal parameters and to var-declared variables inside the “parent” scope).</p><p>Simply put, if there are no default parameters among the formal parameters, then absolutely all variables belong to the <em>Lexical Environment</em> of the <em>Running Execution Context</em>:</p><pre>// example 50. JavaScript</pre><pre>function bar(a) {<br>    var b = 2; // and even the var-declarations (see the algorithm)!<br>    let c = 2;<br>};</pre><pre>bar(1);</pre><blockquote>If the function’s formal parameters do not include any default value initializers then the body declarations are instantiated in the same <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> as the parameters.</blockquote><p>But if there is at least one default parameter among the formal parameters of a function, then all the formal parameters refer to one <em>Variable Environment</em>, all var-declarations inside the body of the function to another one (that replaces the previous one), and all let- and const-declarations to the <em>Lexical Environment</em>.</p><p>But why in this case it is necessary to separate the formal parameters from the var-declarations inside the body of the function? The answer to this question the specification gives in the same 27th step of the algorithm:</p><blockquote>NOTE: A separate <a href="http://www.ecma-international.org/ecma-262/#sec-environment-records">Environment Record</a> is needed to ensure that closures created by expressions in the formal parameter list do not have visibility of declarations in the function body.</blockquote><p>This is exactly what happens in the example 49, morover the specification tries to protect us from such a behavior (though it typically contradicts our direct intentions, but anyway).</p><p>Due to the fact that there is a parameter (foo) among the formal parameters the default value for which is provided, all the bindings declared with the var keyword inside the function’s body (the variable a in the case of the example 49) belong to an absolutely separate <em>Variable Environment</em>.</p><p>Such a separation is necessary because, unlike variables declared using the let keyword, variables declared using the var keyword can override already declared variables:</p><pre>// example 51. JavaScript</pre><pre>var a = 1;<br>var a = 2; // OK</pre><pre>let b = 1;<br>let b = 2; // SyntaxError</pre><p>That is why, if there was not created the separate <em>Variable Environment</em>, then the var a = 2 expression would simply override the variable a created as the formal parameter.</p><p>But since the separate <em>Variable Environment</em> is created, the redefinition of the variable a inside the body of the function is not actually the redefinition, but rather the initialization of a new variable a in the separate <em>Environment Record</em> of the specially created <em>Variable Environment</em>.</p><p>So, when you call the function foo (which is defined in the <em>Environment Rocord</em> of another <em>Variable Environment</em>), the such value of a is returned, which is defined in the <em>Environment Record</em> of the same <em>Variable Environment</em> in which the function foo is defined, i.e. 1.</p><pre>// example 52. JavaScript</pre><pre>(function(a, foo = () =&gt; a) {<br>    a = 2;</pre><pre>    console.log(foo());<br>}(1))</pre><p>However, If we explicitly indicate that we do not want to declare a new variable a, but rather we want to redefine the variable a (which in such case won’t be related to a separate <em>Variable Environment</em>’s <em>Environment Record</em>) already existing in the <em>Environment Record</em> of another <em>Variable Environment</em>, as in the example 52, the output will be the same as expected — 2.</p><p>That is, in this case, the implementation will find that the variable a is not declared in the <em>Environment Record</em> of the current <em>Variable Environment</em> (the one that was created for the function’s body evaluation), so it will refer to the <em>reference to an outer Lexical Environment </em>of the <em>Variable Environment</em> which points to the <em>Lexical Environment</em> in which the formal parameters are defined, therefore changing the value of the formal parameter a.</p><p>Thus, when the function foo is called, it takes the already redefined value of the variable a, which is 2.</p><p>And the last thing. Let’s take another look at the example 49, but this time we do not initialize the variable a with some value, but rather just declare it:</p><pre>// example 53. JavaScript</pre><pre>function bar(a, foo = () =&gt; a) {<br>    var a;</pre><pre>    console.log(a);<br>};</pre><pre>bar(1);</pre><p>In theory, since the variable a is declared inside a separate <em>Variable Environment</em> (separate because there is a default parameter among the formal parameters), its value immediately after the definition should be automatically initialized to undefined (since the variable is declared using the var keyword). That is, the situation should be similar to the one in the example below:</p><pre>// example 54. JavaScript</pre><pre>function foo() {<br>    var a = 1;</pre><pre>    function bar() {<br>        var a;<br>        console.log(a); // undefined<br>    }</pre><pre>    bar();<br>    console.log(a); // 1<br>}</pre><pre>foo();</pre><p>But actually, the value of the variable a in the example 53 is not undefined, but 1. Check it yourself.</p><p>This is because when the variables declared using the var keyword are initialized, if variables of the same name present in the list of formal parameters of a function, they get initialized to the same value that the value of the formal parameter of the same name is (even despite the fact that these variables are in different lexical environments):</p><blockquote>NOTE: vars whose names are the same as a formal parameter, initially have the same value as the corresponding initialized parameter.</blockquote><p>Just bear it in mind.</p><p>So, in addition to its direct purpose, the <em>Variable Environment</em> can also be used as a kind of additional, reserve <em>Lexical Environment</em>, i.e. to create an additional scope that does not allow closures defined in formal parameters to get the value other than the value of the variable to which they are referring. However, of course, the benefits of such a campaign are highly arguable.</p><p>Moreover, they even do not always fulfill their original purpose, as, for example, in cases where the var-declared variables fall into the <em>Lexical Environment</em> record of the <em>Running Execution Context</em>, rather than into the <em>Variable Environment</em> (see the explanation of the example 49).</p><p>Therefore, just keep in mind that one <em>Lexical Environment</em> can not have 2 <em>Environment Records</em> simultaneously, as it formulated (not quite accurately though) in the specification.</p><h4><a href="#4f9c">Summing Up</a></h4><p>I want you to understand that both the <em>Lexical Environment</em> and the <em>Environment Record</em> are separate entities only in terms of the specification. As I said, any <em>Record</em> is just a separate type of the specification. In practice, both the <em>Lexical Environment</em> and the <em>Environment Record</em> are inseparable entities. I’d rather say that in practice the <em>Environment Record</em> <strong>is</strong> the <em>Lexical Environment</em>, however paradoxical that may sound. Simply, the <em>Environment Record</em> is used by the specification to determine the capabilities and functionality of a particular <em>Lexical Environment</em>.</p><p>So when I say that the associations between values and bindings representing these values are stored in the <em>Environment Record</em> of a certain <em>Lexical Environment</em>, then it is so only in terms of the specification (hence in terms of this article). Of course, no one prohibits implementations from using the same approach, but I very much doubt that they do so in fact.</p><ol><li>The <em>Environment Record</em> is a part of the <em>Lexical Environment</em>.</li><li>The <em>Environment Record</em> is used as a repository in which the associations between some real values and bindings representing these values are stored.</li><li>There are several types of the <em>Environment Record</em>, each of which differs in its own way from the others.</li><li>The type of a certain <em>Environment Record</em> determines the type of the <em>Lexical Environment</em> to which this <em>Environment Record</em> belongs.</li></ol><h3><a href="#39c7">In conclusion</a></h3><p><em>You can skip this chapter. No new material is being considered in it. Here I just state my thoughts about writing the article itself.</em></p><p>Initially, I planned to place here a huge example of some code and examine in detail what is happening in it from the specification’s point of view. However, it so happened that writing this article took me much more time and much more energy than I had planned.</p><p>In particular, I spent a little more than a month writing (about 5 weeks), although I planned to do it in about 12 days (2 weeks at maximum). And this is even despite the fact that I was engaged in writing daily (I missed only 4 days), spending an average of 5 hours of free time per day.</p><p>I am not a native speaker of the English language, so expressing my thoughts using it is quite a difficult task for me (although starting from about the middle of the article I began to expound my thoughts in my native language (in Russian), afterwards translating them into English). This was one of the reasons for such a protracted article writing.</p><p>In addition, the size of the article became an important factor. When I first started to write it, I thought that it would be about 2 times less in the end. And since the publication of it will become the first such experience for me (so to speak, my debut), I could not at first assume that maintaining the already written can be so difficult.</p><p>It is rather difficult to keep in mind a list of what I have already said, what I have not said yet, what I planned to say and about what that I planned I had already said. Well, it’s OK, since an experience is never superfluous. Next time I will be more concise in expressing my thoughts.</p><p>I could tell you more about many other interesting things, take a closer look at some points from the specification and go further from the main topic (and yes, unfortunately, I could not tighten a style throughout the whole article), but then the article would be still by an order of magnitude longer and its writing (or, rather, the maintenance of what has already been written) would be an even greater headache.</p><p>To admit honestly, full of enthusiasm and inspiration at first, I really ran out of fuel during the writing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*6nn_nEIYFwOk1OFyPElDFQ.jpeg" /><figcaption>“I’m tired, Boss…” — <a href="https://i.imgur.com/bbgM7Dy.jpg">Source</a></figcaption></figure><p>In the last few days the writing has turned into a struggle with myself, into the struggle to bring it to the end and accept all the inaccuracies, into the struggle with my perfectionism.</p><p>Anyways, be that as it may. Perhaps I’m just too hard on myself. I can not mention everything and can’t tell about everything.</p><p>I hope that this article will at least become a kind of starting point for those who has long been going to read the specification, but could not begin for various reasons.</p><p>Thank you for your attention, and thank you very much if you have read this far. Good luck!</p><p>P.S. I apologize for the misuse of the articles (a and the) (this is my weak point in English).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa6e098e230f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>