<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Aditya Tripathi</title>
    <description>The latest articles on DEV Community by Aditya Tripathi (@odus_ex).</description>
    <link>https://dev.to/odus_ex</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F682669%2F920d66e8-5485-44ef-a857-cf34d9cde00c.jpeg</url>
      <title>DEV Community: Aditya Tripathi</title>
      <link>https://dev.to/odus_ex</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/odus_ex"/>
    <language>en</language>
    <item>
      <title>Javascript "this" binding with examples</title>
      <dc:creator>Aditya Tripathi</dc:creator>
      <pubDate>Sat, 18 Nov 2023 17:31:15 +0000</pubDate>
      <link>https://dev.to/odus_ex/javascript-this-keyword-with-different-bindings-5hb5</link>
      <guid>https://dev.to/odus_ex/javascript-this-keyword-with-different-bindings-5hb5</guid>
      <description>&lt;p&gt;In this article, we will explore a runtime construct for JavaScript language called &lt;code&gt;this&lt;/code&gt;. Compared to other languages, &lt;code&gt;this&lt;/code&gt; behaves differently in JavaScript.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;this&lt;/code&gt; keyword is a way to implicitly pass information of an &lt;em&gt;execution&lt;/em&gt; context to running &lt;em&gt;execution context&lt;/em&gt;. If you are not sure what those terms mean, checkout out my other articles on &lt;a href="https://dev.to/odus_ex/javascript-runtime-and-code-lifecycle-8dn"&gt;JavaScript Runtime&lt;/a&gt; and &lt;a href="https://dev.to/odus_ex/advanced-javascript-mastering-scopes-and-related-concepts-5787"&gt;JavaScript Scopes in-depth&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;It is a way to provide data implicitly between different scopes. &lt;/p&gt;

&lt;p&gt;The value of &lt;code&gt;this&lt;/code&gt; depends on which object it is bound to in runtime. This binding is decided using a set of rules which are always decided on the function call-site, and not where function is declared.&lt;/p&gt;

&lt;p&gt;Let us try to understand this with a very simple example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;me&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Writer&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;you&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Reader&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;printNameImplicit&lt;/span&gt;&lt;span class="p"&gt;(){.&lt;/span&gt; &lt;span class="c1"&gt;// declaration site&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;printNameImplicit&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;call&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;me&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// call-site 1&lt;/span&gt;
&lt;span class="nx"&gt;printNameImplicit&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;call&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;you&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// call-site 2&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;Using &lt;code&gt;call&lt;/code&gt; (more on it later), we &lt;strong&gt;bind&lt;/strong&gt; &lt;code&gt;this&lt;/code&gt; of &lt;code&gt;printNameImplicit&lt;/code&gt; function (or of the scope created by the function) to any object we want. &lt;code&gt;this&lt;/code&gt; value then becomes that object, and &lt;code&gt;name&lt;/code&gt; is displayed accordingly.&lt;/p&gt;

&lt;p&gt;In a way, we "imported" &lt;code&gt;me&lt;/code&gt; and &lt;code&gt;you&lt;/code&gt; object in &lt;code&gt;printNameImplicit&lt;/code&gt; function's scope at runtime. &lt;/p&gt;

&lt;p&gt;Consider another example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;person&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Adam&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;addAge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;age&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
 &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;age&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;age&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;addAddress&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;address&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
 &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;place&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;address&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;addAge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;call&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;person&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nx"&gt;addAddress&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;call&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;person&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;House 1, Street A&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;person&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;//{ name: 'Adam', age: 20, place: 'House 1, Street A' }&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;Using &lt;code&gt;this&lt;/code&gt; we can build up an object or modify its existing properties.&lt;/p&gt;

&lt;h2&gt;
  
  
  Bindings
&lt;/h2&gt;

&lt;p&gt;As we have seen above, &lt;code&gt;call&lt;/code&gt; helps us bind &lt;code&gt;this&lt;/code&gt; of a function to an object. It takes two parameters, the first being the object we need &lt;code&gt;this&lt;/code&gt; to be bound to, the second is the argument required by the function whose &lt;code&gt;this&lt;/code&gt; is being bound.&lt;/p&gt;

&lt;p&gt;But what happens when we have multiple arguments for the function? We can pass subsequent parameters to &lt;code&gt;call&lt;/code&gt; or&lt;br&gt;
we can use a  very similar construct called &lt;code&gt;apply&lt;/code&gt;. It is almost identical to &lt;code&gt;call&lt;/code&gt; except that its second parameter is an array of values, representing multiple parameters of the function. If we modify our above example, by combining the functions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;person&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Adam&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;addAddressAndAge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;address&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;age&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
 &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;place&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;address&lt;/span&gt;
 &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;age&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;age&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;addAddressAndAge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;apply&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;person&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;House 1, Street A&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
&lt;span class="c1"&gt;// or addAddressAndAge.call(person, 'House 1, Street A', 20);&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;person&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// { name: 'Adam', age: 20, place: 'House 1, Street A' }&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;As mentioned above &lt;code&gt;call&lt;/code&gt; and &lt;code&gt;apply&lt;/code&gt; are methods are a way to bind &lt;code&gt;this&lt;/code&gt; to an object. By default, in non-strict mode, &lt;code&gt;this&lt;/code&gt; is bound to the Global Object. In strict mode, &lt;code&gt;this&lt;/code&gt; is bound to nothing and hence its value is &lt;code&gt;undefined&lt;/code&gt;. This scenario is called as &lt;em&gt;default binding&lt;/em&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// non-strict mode&lt;/span&gt;
&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(){&lt;/span&gt;
 &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="c1"&gt;// 10&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, &lt;code&gt;this&lt;/code&gt; is bound to global scope. In strict mode, the result would be &lt;code&gt;undefined&lt;/code&gt; instead.&lt;/p&gt;

&lt;h3&gt;
  
  
  Implicit Binding
&lt;/h3&gt;

&lt;p&gt;Implicit binding refers to &lt;code&gt;this&lt;/code&gt; being bound to the object decorated on the call-site of the function. Consider the following example:&lt;br&gt;
&lt;/p&gt;

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

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;person&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Adam&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;printName&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;printName&lt;/span&gt; &lt;span class="c1"&gt;// implicit 'this' binding&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;person&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;printName&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;  &lt;span class="c1"&gt;// call site decorated with person object&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;When we modify object &lt;code&gt;person&lt;/code&gt; to include printName inside it, the &lt;code&gt;this&lt;/code&gt; of &lt;code&gt;printName&lt;/code&gt; is implicitly bound to &lt;code&gt;person&lt;/code&gt; if the function call is made using the &lt;code&gt;person&lt;/code&gt; object.&lt;/p&gt;

&lt;p&gt;Also note that only the closest object reference at call site is bound to &lt;code&gt;this&lt;/code&gt;. For eg. if we do:&lt;br&gt;
&lt;/p&gt;

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

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;person&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Adam&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;printName&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;printName&lt;/span&gt; &lt;span class="c1"&gt;// implicit 'this' binding&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;anotherPerson&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Eve&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;friend&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;person&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;anotherPerson&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;friend&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;printName&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// Adam&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;friend&lt;/code&gt;, i.e. &lt;code&gt;person&lt;/code&gt; object will be bound to 'this' because it is closer to &lt;code&gt;printName&lt;/code&gt; function call. &lt;/p&gt;

&lt;p&gt;Implicit bindings are lost when the call-site is undecorated. When implicit bindings are lost, they fallback to default binding.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Eve&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;printName&lt;/span&gt;&lt;span class="p"&gt;(){&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;person&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Adam&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;printName&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;printName&lt;/span&gt; &lt;span class="c1"&gt;// implicit 'this' binding&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nf"&gt;printName&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="c1"&gt;// Eve, in non-strict mode, undefined in strict&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;Implicit bindings are also easily lost or re-bound in-case of assignments and callbacks.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Eve&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;printName&lt;/span&gt;&lt;span class="p"&gt;(){&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;person&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Adam&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;printName&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;printName&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nf"&gt;setTimeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;person&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;printName&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// Eve, implicit binding lost&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;In other words it do not automatically forms a closure with the bound object. &lt;/p&gt;

&lt;h3&gt;
  
  
  Explicit Binding
&lt;/h3&gt;

&lt;p&gt;Explicit binding, as the name suggests, is when we explicitly bind &lt;code&gt;this&lt;/code&gt; to an object using constructs like &lt;code&gt;call&lt;/code&gt;, &lt;code&gt;apply&lt;/code&gt; or &lt;code&gt;bind&lt;/code&gt; which we saw above. Unlike implicit binding, explicit binding constructs allow us to bind &lt;code&gt;this&lt;/code&gt; without actually altering the object its bound to.&lt;br&gt;
&lt;/p&gt;

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

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;person&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Adam&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;age&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;32&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;printName&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;call&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;person&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Adam&lt;/span&gt;
&lt;span class="nx"&gt;printName&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;apply&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;person&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Adam&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;However, explicit binding does not cure the problem of losing our bindings and is fragile like implicit binding. To tackle this, we can perform a certain type of explicit binding called as &lt;em&gt;hard explicit binding&lt;/em&gt; or just &lt;em&gt;hard binding&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Hard binding wraps the call-site in a wrapper function, this makes sure that the scope in which a function's &lt;code&gt;this&lt;/code&gt; is bound to the target object is not influenced by other scope.&lt;br&gt;
&lt;/p&gt;

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

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;person&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Adam&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;age&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;32&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;hardBind&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;function &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;targetFunction&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;targetObject&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
  &lt;span class="nx"&gt;targetFunction&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;call&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;targetObject&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nf"&gt;setTimeout&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;hardBind&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;printName&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;person&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Adam&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;Here, we provide a wrapping function, so that our calling code (which is &lt;code&gt;setTimeout&lt;/code&gt;) is forced to perform binding through that wrapper function only, making sure that whenever &lt;code&gt;printName&lt;/code&gt; is called, its &lt;code&gt;this&lt;/code&gt; is bound to the &lt;code&gt;personObject&lt;/code&gt;. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The above example utilises &lt;em&gt;Closures&lt;/em&gt;. If you do not understand how? Take a look at my article on closure: &lt;a href="https://dev.to/odus_ex/advanced-javascript-closures-4j2p"&gt;JavaScript Closures with examples&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The wrapper function is a common binding design pattern in JavaScrip and hence it is supplied as a default construct by the language in the name of &lt;code&gt;bind&lt;/code&gt;. The &lt;code&gt;bind&lt;/code&gt; returns a function which is called every-time we want to perform hard binding.&lt;br&gt;
&lt;/p&gt;

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

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;person&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Adam&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;age&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;32&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;hardBind&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;printName&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;bind&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;person&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="nf"&gt;setTimeout&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;hardBind&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;printName&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;person&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Adam&lt;/span&gt;

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  &lt;code&gt;new&lt;/code&gt; Binding
&lt;/h3&gt;

&lt;p&gt;To understand &lt;code&gt;this&lt;/code&gt; binding created by &lt;code&gt;new&lt;/code&gt; operator, let us quickly refresh how &lt;code&gt;new&lt;/code&gt; works.&lt;/p&gt;

&lt;p&gt;Calling any function with &lt;code&gt;new&lt;/code&gt; makes it a &lt;em&gt;constructor call&lt;/em&gt;. A constructor calls returns a newly created object, unless the function being called returns its own object. &lt;/p&gt;

&lt;p&gt;The &lt;code&gt;new&lt;/code&gt; operator binds the constructor function's &lt;code&gt;this&lt;/code&gt; to this newly created object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;Person&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;age&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
  &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;age&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;age&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;person&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Person&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Adam&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;32&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;person&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// Person { name: 'Adam', age: 32 }&lt;/span&gt;

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Arrow Functions
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;this&lt;/code&gt; behaves differently from arrow functions. Unlike regular functions arrow functions do not have their own &lt;code&gt;this&lt;/code&gt;, they form a closure with the &lt;code&gt;this&lt;/code&gt; value of enclosing scope. This behaviour is sometimes useful when we do not want to shadow &lt;code&gt;this&lt;/code&gt; value by creating our own for each function declared.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;obj&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
 &lt;span class="c1"&gt;// implicitly bound this  &lt;/span&gt;
 &lt;span class="nf"&gt;getThisGetter&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;getter&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;getter&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;


&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;fn&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;obj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getThisGetter&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;fn&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="nx"&gt;obj&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// true&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;fn2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;obj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;getThisGetter&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;fn2&lt;/span&gt;&lt;span class="p"&gt;()()&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="nx"&gt;globalThis&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// true in non-strict mode&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;this&lt;/code&gt; keyword in JavaScript plays a crucial role in determining the runtime binding of functions to objects. Unlike many other programming languages, &lt;code&gt;this&lt;/code&gt; in JavaScript is dynamic and relies on the rules set during the function call-site, not the declaration. We explored how this can be explicitly bound using methods like call, apply, and bind, allowing for flexibility in managing the context in which functions are executed.&lt;/p&gt;

&lt;p&gt;That's all for now. Until next time :)&lt;/p&gt;

</description>
    </item>
    <item>
      <title>JavaScript Closures with examples</title>
      <dc:creator>Aditya Tripathi</dc:creator>
      <pubDate>Sat, 30 Sep 2023 07:03:18 +0000</pubDate>
      <link>https://dev.to/odus_ex/advanced-javascript-closures-4j2p</link>
      <guid>https://dev.to/odus_ex/advanced-javascript-closures-4j2p</guid>
      <description>&lt;p&gt;In JavaScript, &lt;em&gt;Closure&lt;/em&gt; is a phenomena of a code getting executed outside its lexical scope. They happen because of writing lexically structured code.&lt;/p&gt;

&lt;p&gt;In other words, Closures let us access a foreign parent scope even after it has exited the runtime. Closures are created every-time we create a scope. They are strongly associated with scopes so before exploring Closures, let us refresh what lexical scopes are.&lt;/p&gt;

&lt;h3&gt;
  
  
  Lexical Scope
&lt;/h3&gt;

&lt;p&gt;You might be already familiar with the concept of Scope and Execution contexts in JavaScript. If you would like a refresher on these topic, consider a recent article I wrote, similar to this: &lt;a href="https://dev.to/odus_ex/advanced-javascript-mastering-scopes-and-related-concepts-5787"&gt;Mastering JavaScript Scopes&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's cover the important highlights here briefly. &lt;/p&gt;

&lt;p&gt;JavaScript associates important execution details of a program with the place they are declared in the source code, pertaining to the visibility of declared entities. At author time, these are called &lt;em&gt;Scopes&lt;/em&gt;. At runtime these become &lt;em&gt;Execution Contexts&lt;/em&gt; and are called on &lt;em&gt;Execution Stack&lt;/em&gt; one after another to hold the information required for successful execution of the code.&lt;/p&gt;

&lt;p&gt;Consider the following example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;greet&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;typeOfGreeting&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;nameInUpper&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;toUpperCase&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;sayHello&lt;/span&gt;&lt;span class="p"&gt;(){&lt;/span&gt;
 &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;greetings&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;`Hello &lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;nameInUpper&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt; :)`&lt;/span&gt;
 &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;greetings&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;sayHi&lt;/span&gt;&lt;span class="p"&gt;(){&lt;/span&gt;
 &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;greetings&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;`Hi &lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;nameInUpper&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;!`&lt;/span&gt; 
 &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;greetings&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;typeOfGreeting&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;hi&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="nx"&gt;sayHi&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;sayHello&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;In the above example, &lt;code&gt;greet&lt;/code&gt; function creates a functional scope. This scope contains two other functions, &lt;code&gt;sayHello&lt;/code&gt; and &lt;code&gt;sayHi&lt;/code&gt; along with &lt;code&gt;greet&lt;/code&gt; arguments and variable &lt;code&gt;nameInUpper&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Note that nested scope can access declared entities of the enclosing scope. This means both &lt;code&gt;sayHello&lt;/code&gt; and &lt;code&gt;sayHi&lt;/code&gt; can access entities of &lt;code&gt;greet&lt;/code&gt; (and Global Scope).&lt;/p&gt;

&lt;p&gt;However, a parent scope cannot access entities declared in its nested scopes. So &lt;code&gt;greet&lt;/code&gt; doesn't have access to entities declared inside &lt;code&gt;sayHi&lt;/code&gt; and &lt;code&gt;sayHello&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Also, note that two &lt;code&gt;greetings&lt;/code&gt; variables are created without conflict because they are in separate scopes, i.e. one in &lt;code&gt;sayHi&lt;/code&gt; and one in &lt;code&gt;sayHello&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Closures in action
&lt;/h3&gt;

&lt;p&gt;Now that we understand scopes, lets explore how closures "happen" as a result of writing lexically scoped code.&lt;/p&gt;

&lt;p&gt;When we execute &lt;code&gt;greet&lt;/code&gt; like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;greetBen&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;greet&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;ben&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;hi&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;greetBen&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt; &lt;span class="c1"&gt;// Hi BEN!&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;We notice a rather peculiar behaviour. On executing &lt;code&gt;greetBen&lt;/code&gt; we are able to remember entities declared in &lt;code&gt;greet&lt;/code&gt; and use them at later point of time in code (i.e. in &lt;code&gt;console.log()&lt;/code&gt;), even when &lt;code&gt;greet&lt;/code&gt; has completed its execution well before executing &lt;code&gt;greetBen&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This is Closures! &lt;code&gt;greetBen&lt;/code&gt; is said to have formed a closure on &lt;code&gt;greet&lt;/code&gt;. This allows &lt;code&gt;greetBen&lt;/code&gt; to keep the entities declared in &lt;code&gt;greet&lt;/code&gt; "alive" (i.e. stop being garbage collected), even after its execution context has been popped out of execution call stack.&lt;/p&gt;

&lt;p&gt;For better understanding, consider a slightly modified example below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;greetBen&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;greet&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;ben&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;hi&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nx"&gt;setTimeOut&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;greetBen&lt;/span&gt;&lt;span class="p"&gt;()),&lt;/span&gt; &lt;span class="mi"&gt;5000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code prints the same output as before but after 5 seconds, re-enforcing our understanding of keeping the entities alive and dynamically accessing a them at runtime even when the scope in which they were declared is not available.&lt;/p&gt;

&lt;h3&gt;
  
  
  Closure Examples
&lt;/h3&gt;

&lt;p&gt;Now that we have seen some basic examples, let us discuss a couple of advanced ones.&lt;/p&gt;

&lt;p&gt;Consider the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;iife1&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;iife2&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// What is logged?&lt;/span&gt;
  &lt;span class="p"&gt;})(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;})(&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After a good look, we recognise that &lt;code&gt;iife2&lt;/code&gt; forms a closure with &lt;code&gt;iife1&lt;/code&gt; and hence has access to &lt;code&gt;a&lt;/code&gt;. The output of the program will be 100.&lt;/p&gt;

&lt;p&gt;Consider another code-snippet:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;setTimeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;print&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;i&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// What is logged?&lt;/span&gt;
  &lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because &lt;code&gt;var&lt;/code&gt; declarations do not create block scopes, the closure formed by &lt;code&gt;print&lt;/code&gt; on the enclosing scope (i.e. Global Scope) will get the final updated value of &lt;code&gt;i&lt;/code&gt;. Hence the above code will print &lt;code&gt;3&lt;/code&gt;, &lt;code&gt;3&lt;/code&gt;, &lt;code&gt;3&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If we were to replace &lt;code&gt;var&lt;/code&gt; with &lt;code&gt;let&lt;/code&gt;, then the enclosing scope for &lt;code&gt;print&lt;/code&gt; will be &lt;code&gt;for&lt;/code&gt; block instead of the Global Scope, as &lt;code&gt;let&lt;/code&gt; creates a block scope. On each loop iteration, a new scope will be created and the updated &lt;code&gt;i&lt;/code&gt; value will be generated for each new scope, resulting in sustaining each value as the loop iterates. Hence the output would then be &lt;code&gt;0&lt;/code&gt;, &lt;code&gt;1&lt;/code&gt; and &lt;code&gt;2&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;I have borrowed these examples from an amazing blog by &lt;em&gt;Dimitri Palvutin&lt;/em&gt;. You can find more of such examples by visiting his write-up &lt;a href="https://dmitripavlutin.com/javascript-closures-interview-questions/"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Design Patterns
&lt;/h3&gt;

&lt;p&gt;JavaScript developers have been utilising Closures to create some of the most famous design patterns in the language. Some of them are discussed below:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Functions as first class citizens&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We are able to pass around functions in JavaScript due to closures. A function as argument forms the closure with the calling function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;doMath&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;operation&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;operation&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;addFive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;number&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;number&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;multiplyFive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;number&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;number&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;doMath&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;addFive&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt; &lt;span class="c1"&gt;// 10&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;doMath&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;multiplyFive&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt; &lt;span class="c1"&gt;// 25&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;Here, &lt;code&gt;operation&lt;/code&gt; function is able to form a closure with &lt;code&gt;doMath&lt;/code&gt; enabling us to operate on &lt;code&gt;doMath&lt;/code&gt; argument. It is using this behaviour, we are able to implement callbacks and event-listeners in the language.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Module Pattern&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Closures are utilised to create data encapsulation and data abstraction. Consider the example below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;CounterModule&lt;/span&gt;&lt;span class="p"&gt;(){&lt;/span&gt;

&lt;span class="c1"&gt;// Data Encapsulation&lt;/span&gt;
&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;counter&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;reset&lt;/span&gt;&lt;span class="p"&gt;(){&lt;/span&gt;
 &lt;span class="nx"&gt;counter&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;increment&lt;/span&gt;&lt;span class="p"&gt;(){&lt;/span&gt;
 &lt;span class="nx"&gt;counter&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;decrement&lt;/span&gt;&lt;span class="p"&gt;(){&lt;/span&gt;
 &lt;span class="nx"&gt;counter&lt;/span&gt;&lt;span class="o"&gt;--&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;getCounter&lt;/span&gt;&lt;span class="p"&gt;(){&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;counter&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;reset&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;increment&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;decrement&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;getCounter&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="p"&gt;}&lt;/span&gt;


&lt;span class="c1"&gt;// Data Abstraction&lt;/span&gt;
&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;reset&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;increment&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;decrement&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;getCounter&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;CounterModule&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example above, we created a &lt;code&gt;CounterModule&lt;/code&gt; with a private implementation detail &lt;code&gt;counter&lt;/code&gt;. We then define operations allowed to be performed on this private data by using functions like &lt;code&gt;reset&lt;/code&gt;, &lt;code&gt;increment&lt;/code&gt; and &lt;code&gt;decrement&lt;/code&gt; because these function form closure with &lt;code&gt;CounterModule&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Thats all what Closures are!&lt;/p&gt;

&lt;p&gt;I hope that this article helped you understand Closures and how it is utilised in everyday JavaScript code to implement some of the most important language behaviours and characteristics. &lt;/p&gt;

&lt;p&gt;Until next time. Happy Hacking! :)&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Mastering Scopes in JavaScript</title>
      <dc:creator>Aditya Tripathi</dc:creator>
      <pubDate>Sun, 10 Sep 2023 09:25:29 +0000</pubDate>
      <link>https://dev.to/odus_ex/advanced-javascript-mastering-scopes-and-related-concepts-5787</link>
      <guid>https://dev.to/odus_ex/advanced-javascript-mastering-scopes-and-related-concepts-5787</guid>
      <description>&lt;p&gt;In this article, I aim to provide in-depth explanation for Scope and related concepts like scope-lookups, hoisting and scope-chaining, etc in JavaScript.&lt;/p&gt;

&lt;p&gt;Before we begin, it is important to understand the technical foundation of the language, most notably, the &lt;em&gt;JIT-compiled&lt;/em&gt; nature. I already wrote some articles on topics: &lt;a href="https://dev.to/odus_ex/a-short-technical-introduction-to-javascript-13a0"&gt;A technical introduction to JavaScript&lt;/a&gt; and &lt;a href="https://dev.to/odus_ex/javascript-runtime-and-code-lifecycle-8dn"&gt;JavaScript runtime and code lifecycle&lt;/a&gt; which you can checkout. Also, note that we are going to take a bottom up approach for understanding the concepts. Hence first we will walk through (briefly), a sample code life-cycle and then try to understand the concepts. With that said, lets get started!&lt;/p&gt;

&lt;p&gt;As JavaScript is a JIT-compiled, it goes through two steps before finally getting executed: &lt;strong&gt;The Compilation Step (or Creation Phase)&lt;/strong&gt; where the source code is turned into a non-executable intermediate code called &lt;em&gt;byte-code&lt;/em&gt; and then &lt;strong&gt;The Interpretation Step (or Execution Phase)&lt;/strong&gt; where the byte-code is converted to &lt;em&gt;machine-code&lt;/em&gt; for execution. &lt;/p&gt;

&lt;p&gt;Below we will walk through these two processes using some sample examples. They are already covered in depth in the articles mentioned above.&lt;/p&gt;

&lt;p&gt; &lt;br&gt;
 &lt;/p&gt;
&lt;h2&gt;
  
  
  JavaScript Compilation: Creation Phase
&lt;/h2&gt;

&lt;p&gt;When JavaScript code is in it's compilation step it creates an Abstract Syntax tree (AST) using tokens. When the AST is being created, it contains empty objects for identifiers or variables, instead of the value contained by them. Below is an estimated AST diagram for a sample code:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--MxyGctbT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/azpibnqi7xk8iuo6torx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--MxyGctbT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/azpibnqi7xk8iuo6torx.png" alt="JavaScript Abstract Syntax Tree or AST" width="800" height="725"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the above diagram, the &lt;em&gt;proxy&lt;/em&gt; represents the empty objects. As we will see, these proxy objects are later replaced with identifier's memory reference.&lt;/p&gt;

&lt;p&gt;Along with AST creation, the compilation process also creates &lt;strong&gt;&lt;em&gt;Environment Records&lt;/em&gt;&lt;/strong&gt;, also referred as just &lt;em&gt;environments&lt;/em&gt;. Environment Record is a &lt;em&gt;specification type&lt;/em&gt;, an object like structure containing key-value pairs. These environment records hold information regarding identifier bindings, with some other meta data. Most importantly, they contain identifier's memory reference, which is later used to fetch the value contained in it. It also contains an &lt;code&gt;outer&lt;/code&gt; variable, pointing to other environment record. This extra information is used for creating &lt;em&gt;scope chains&lt;/em&gt;. We will explore them later in the article.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--n195lm-y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4dlwics2fnuz3egndtjj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--n195lm-y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4dlwics2fnuz3egndtjj.png" alt="JavaScript Environment Records" width="800" height="725"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;There are many types of environment records.A &lt;strong&gt;&lt;em&gt;Lexical Environment&lt;/em&gt;&lt;/strong&gt; is an environment record which represents lexically written code. For our use-case we are going to use the terms environment record and lexical environments interchangeably. &lt;/p&gt;

&lt;p&gt;As we can see from the diagram above, there are two types of environments created: &lt;em&gt;Global&lt;/em&gt; and &lt;em&gt;Local&lt;/em&gt;. A Global environment is always created when the code execution is started. Local environments are created when compiler encounter code-blocks in the code. Code-blocks are code snippets inside curly braces (&lt;code&gt;{...}&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--wfAnez6y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/srzob2v4wr6wd4769fz7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--wfAnez6y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/srzob2v4wr6wd4769fz7.png" alt="Code block in JavaScript" width="800" height="725"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;However, not every code block encountered by the compiler creates a lexical environment. These are only created under certain conditions, like when the compiler encounters a code-block associated with a function declaration or a code-block containing &lt;code&gt;let&lt;/code&gt; or &lt;code&gt;const&lt;/code&gt; variable declarations or for a code-block associated with &lt;code&gt;catch&lt;/code&gt; construct, etc... &lt;/p&gt;

&lt;p&gt;To summarise, an environment record is created for code-blocks under certain conditions. Whenever these environments are created the identifier information is stored in these environments.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Environment Record&lt;/em&gt; is a &lt;strong&gt;specification type&lt;/strong&gt;, meaning it represent an abstract concept in the ECMA-262 specification and is hard to accurately represent as vendors are free to implement them as they like provided their behaviour remains unchanged. For more information on environment records, refer to &lt;a href="https://tc39.es/ecma262/multipage/executable-code-and-execution-contexts.html"&gt;this&lt;/a&gt; document of the specification.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Once the compiler has a finished generating AST and all the relevant environment records for the code, the next step in compilation process is to start generating byte-code using the information present in environment records. This step is also called &lt;em&gt;parsing&lt;/em&gt;. &lt;/p&gt;

&lt;p&gt;In parsing, the AST is traversed, node-by-node, and byte-code is generated by filling the proxy object in AST, with identifier's memory reference (and not its value) by referring the corresponding environment record (a lookup). These identifier references are later used for resolving actual values held by identifiers in execution phase (another lookup).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--K2_v6rZV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jyy3lzgsw6zwtcd5wbqj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--K2_v6rZV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jyy3lzgsw6zwtcd5wbqj.png" alt="JavaScript Byte-code Generation" width="800" height="418"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once the byte-code is generated, the creation phase ends and the execution phase begins.&lt;/p&gt;

&lt;p&gt; &lt;br&gt;
 &lt;/p&gt;
&lt;h2&gt;
  
  
  JavaScript Interpretation: Execution Phase
&lt;/h2&gt;

&lt;p&gt;The byte-code is given as input to the interpreter which is responsible for the execution, i.e. converting the platform independent byte-code to platform dependent machine-code (0s and 1s). This is where &lt;strong&gt;Execution Contexts&lt;/strong&gt; come into picture. &lt;/p&gt;

&lt;p&gt;Similar to lexical environment, Execution Context is an abstract concept (again, a &lt;em&gt;specification type&lt;/em&gt;) used to track the execution of a JavaScript program. We can define Execution Context as a "runtime form" of lexical environment with some extra information to execute a JavaScript code successfully. Each execution context contains the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A lexical environment&lt;/li&gt;
&lt;li&gt;Value of &lt;code&gt;this&lt;/code&gt; &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When a chunk of byte-code is being interpreted/executed to machine-code, the corresponding execution context (i.e. a lexical environment and &lt;code&gt;this&lt;/code&gt; binding information) is &lt;em&gt;pushed&lt;/em&gt; onto a stack data-structure called &lt;em&gt;Execution Context Stack&lt;/em&gt;, otherwise called as call-stack. The execution context on top of this stack is called a &lt;em&gt;running execution context&lt;/em&gt;, because it represents the code being run at the current moment of time. For each running execution context the interpreter start performing lookups for values, contained in identifier references (added in the byte-code previously). &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--K6o4pfJa--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mrf0ks44r6w5ja8igl9f.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--K6o4pfJa--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mrf0ks44r6w5ja8igl9f.png" alt="JavaScript Execution Context" width="800" height="485"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the diagram above, the blocks highlighted with orange represent how execution contexts are used to fetch runtime values required to executed the program. The highlighted block in top of call-stack is represents running execution context.&lt;br&gt;
The JS interpreter fetches the value using identifier's memory reference. The byte-code is then interpreted to machine-code and the code is finally executed.&lt;/p&gt;

&lt;p&gt; &lt;br&gt;
 &lt;/p&gt;

&lt;p&gt;Now that we understand both the phases we are ready to explore JavaScript Scopes and different terminologies associated with it.&lt;/p&gt;

&lt;p&gt;We are going to dissect the following sample code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;c&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;foo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
 &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
  &lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="nx"&gt;d&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
 &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;e&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="nx"&gt;c&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
 &lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;d&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="nx"&gt;foo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;c&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Scopes
&lt;/h2&gt;

&lt;p&gt;When we run the above code, the first step it goes through is compilation. We already know that in compilation, AST and lexical environments are generated. &lt;br&gt;
&lt;strong&gt;Scope&lt;/strong&gt; refer to the visibility of an identifier in a particular code-block (or in specification terms, a lexical environment). From this perspective, Scopes are nothing but a static representation of lexical environments.&lt;br&gt;
We also discussed that lexical environments are created for code-blocks with some rules, let discuss two most important conditions where scopes are generated by the compiler.&lt;/p&gt;

&lt;p&gt;Compiler creates a new scope for a code-block which contains at-least one &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt; declaration or when a code-block is associated with a function declaration. &lt;br&gt;
A code-block with &lt;code&gt;let&lt;/code&gt; or &lt;code&gt;const&lt;/code&gt; declaration gets its own scope (lexical environment), hence we say &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt; are &lt;em&gt;block&lt;/em&gt; scoped, but if we use &lt;code&gt;var&lt;/code&gt;, the identifiers are associated with the most recent 'outer' functional lexical environment. Hence &lt;code&gt;var&lt;/code&gt; is always functionally scoped.&lt;/p&gt;

&lt;p&gt;The following diagram represents the creation of scopes for different identifiers for our sample code above. Note that I have intentionally left the &lt;code&gt;outer&lt;/code&gt; field empty. We will come back to this when exploring &lt;em&gt;scope chaining&lt;/em&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--yqTGmcDE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qggtjs89rtaa3hr58sn6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--yqTGmcDE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qggtjs89rtaa3hr58sn6.png" alt="JavaScript Scope with Example" width="800" height="577"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;c&lt;/code&gt; and &lt;code&gt;foo&lt;/code&gt; are created in Global Lexical Environment (Global Scope), represented in blue.&lt;/li&gt;
&lt;li&gt;Because &lt;code&gt;foo&lt;/code&gt; is a function a new lexical environment is created for the code block associated with it, represented in green. This contains &lt;code&gt;a&lt;/code&gt;, &lt;code&gt;d&lt;/code&gt; and &lt;code&gt;e&lt;/code&gt; but not &lt;code&gt;b&lt;/code&gt;. &lt;/li&gt;
&lt;li&gt;For the &lt;code&gt;if&lt;/code&gt; statement, a new lexical environment is created because it is associated with a code-block containing a &lt;code&gt;let&lt;/code&gt; declaration (block scoped). Hence, &lt;code&gt;b&lt;/code&gt; is present inside this lexical environment instead of &lt;code&gt;foo&lt;/code&gt;'s, represented by purple. Note that this is not true for &lt;code&gt;else&lt;/code&gt; because it doesn't contain any &lt;code&gt;let&lt;/code&gt; or &lt;code&gt;const&lt;/code&gt; declared variables.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That's all what scopes are. A word which represents the visibility of an identifier in the code or a representation of static lexical environments.&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;
&lt;h2&gt;
  
  
  Hoisting
&lt;/h2&gt;

&lt;p&gt;Before defining hoisting, let us understand the memory allocation process used by JavaScript as it plays a crucial role in the definition.&lt;/p&gt;

&lt;p&gt;In compilation phase, identifiers are allocated memory, however not every identifier is treated the same. Identifiers associated with &lt;code&gt;function&lt;/code&gt; and &lt;code&gt;var&lt;/code&gt; declarations are allocated memory &lt;strong&gt;and&lt;/strong&gt; are initialised. Identifiers associated with &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt; are allocated memory but are &lt;strong&gt;not&lt;/strong&gt; initialised with any value. They are said to be allocated in a &lt;strong&gt;Temporal Dead Zone or TDZ&lt;/strong&gt;. Because there is no initialisation for these variables, they cannot be 'accessed' before they are initialised.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;function&lt;/code&gt; declarations are straight away initialised to the associated code-block. &lt;code&gt;var&lt;/code&gt; are initialised with &lt;code&gt;undefined&lt;/code&gt;. For example in our sample code &lt;code&gt;var c&lt;/code&gt; is initialised with &lt;code&gt;10&lt;/code&gt; but compiler anyway initialises it with &lt;code&gt;undefined&lt;/code&gt; once and while execution, when interpreter gets to the line &lt;code&gt;var c = 10&lt;/code&gt; it is re-assigned to &lt;code&gt;10&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Because of this behaviour &lt;code&gt;var&lt;/code&gt; variables are accessible in the statements with a value of &lt;code&gt;undefined&lt;/code&gt; even before their actual declaration or assignment happens in the code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;msg&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;// undefined&lt;/span&gt;
&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;msg&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Hello World&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;//undefined replaced with 'Hello World'&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;With this understanding, let us define Hoisting.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Hoisting&lt;/em&gt;&lt;/strong&gt; is a phenomena to use an identifier before declaring it, causing side-effects in the program. Note that the definition is generally opinionated but the above provided definition is quite generic and should work for most of the opinions. &lt;br&gt;
Newer constructs like &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt; are hoisted but not initialised with a value and hence cannot be accessed before they are declared.&lt;br&gt;
&lt;code&gt;var&lt;/code&gt; identifiers are hoisted and initialised with &lt;code&gt;undefined&lt;/code&gt; value.&lt;br&gt;
Identifiers associated with function declarations are also hoisted, but are not initialised with &lt;code&gt;undefined&lt;/code&gt;, instead they are assigned the code-block represented by the function declaration.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In English language, hoisting means lifting objects with ropes and pulleys. But JavaScript doesn't actually lift or pull any variables or functions up in the code-structure, contrary to what we generally read about hoisting. No declaration is 'moved' on top of scope or in-fact anywhere. It is just a naive way (and misleading) of explaining the concept.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Hoisting happens per scope (lexical environment), so for any code-block whose lexical environment is being created, the block is first 'scanned' for all the declarations and all variable declarations are allocated some memory. &lt;code&gt;undefined&lt;/code&gt; is assigned to identifiers declared using &lt;code&gt;var&lt;/code&gt;. &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt; declared identifiers are placed in a &lt;em&gt;TDZ&lt;/em&gt; instead, without any initialisation. &lt;/p&gt;

&lt;p&gt;Now that we understand hoisting, let us understand a hoisting scenario in our sample code. When we run the sample code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;c&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;foo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
 &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
  &lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="nx"&gt;d&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;  &lt;span class="c1"&gt;// 20 undefined&lt;/span&gt;
 &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;e&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="nx"&gt;c&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
 &lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;d&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="nx"&gt;foo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;c&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;d&lt;/code&gt; is hoisted and initialised with a value of &lt;code&gt;undefined&lt;/code&gt; for &lt;code&gt;foo&lt;/code&gt;'s lexical environment (scope), and hence prints &lt;code&gt;undefined&lt;/code&gt; because when &lt;code&gt;d&lt;/code&gt; was accessed in &lt;code&gt;console.log&lt;/code&gt; it hasn't been re-initialised with &lt;code&gt;100&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Scope Lookups and Scope Chains
&lt;/h2&gt;

&lt;p&gt;Whenever a JavaScript code is compiled and executed, a global scope is always created. Remember that execution contexts are nothing but lexical environments (scope) with some extra information (&lt;code&gt;this&lt;/code&gt; binding) and resolved identifier values instead of identifier references.&lt;/p&gt;

&lt;p&gt;There are two types of lookups performed by JavaScript. The first one happens at compile time, which looks up identifier name against a memory reference to check what memory reference is allocated to the corresponding identifier name. The second look up happens at runtime, where these memory references are resolved for the actual values they contain.&lt;/p&gt;

&lt;p&gt;Lets try to elaborate on this with our sample code example: &lt;/p&gt;

&lt;p&gt;A &lt;em&gt;LHS&lt;/em&gt; lookup happens in creation phase (or compile time), when we lookup for an identifier memory reference against its name (&lt;code&gt;c&lt;/code&gt;, &lt;code&gt;b&lt;/code&gt;, &lt;code&gt;d&lt;/code&gt; ...etc). The proxy objects in AST are replaced  with these memory references in byte-code, fetched after a successful lookup.&lt;/p&gt;

&lt;p&gt;A &lt;em&gt;RHS&lt;/em&gt; lookup happens in execution phase, when we want to resolve an memory reference of an identifier (which was looked up in the above step) for the actual value contained by that identifier (&lt;code&gt;10&lt;/code&gt;, &lt;code&gt;20&lt;/code&gt;, &lt;code&gt;100&lt;/code&gt; ...etc).&lt;/p&gt;

&lt;p&gt;An unsuccessful lookup results in &lt;code&gt;ReferenceError&lt;/code&gt; in strict mode, because it means the name of the variable we are looking for has never have been declared in any lexical environment of the code. In non-strict mode, unsuccessful LHS lookup will automatically create a &lt;code&gt;var&lt;/code&gt; variable with the name of identifier being looked up.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;
&lt;span class="c1"&gt;// strict mode&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// 10&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// lookup fails for `b`, ReferenceError&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;To understand the concept better, lets take some examples of LHS and RHS lookups from our sample code. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;var c = 10&lt;/code&gt; will result in a LHS lookup for &lt;code&gt;c&lt;/code&gt;. When &lt;code&gt;foo(c)&lt;/code&gt; or &lt;code&gt;console.log(e,c)&lt;/code&gt; is called with &lt;code&gt;c&lt;/code&gt; as argument (assuming the &lt;code&gt;else&lt;/code&gt; block executes), a RHS lookup will happen to pass the copy of the value contained in &lt;code&gt;c&lt;/code&gt; as function argument to &lt;code&gt;foo&lt;/code&gt; or &lt;code&gt;console.log&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Similarly, &lt;code&gt;let b = 20&lt;/code&gt; will trigger a LHS lookup, &lt;code&gt;console.log(b,c)&lt;/code&gt; will result in a RHS lookup.&lt;/p&gt;

&lt;p&gt;To summarise, LHS lookups 'checks' for memory references against identifier names. A RHS lookup 'checks' for the value contained in a memory reference, already verified by LHS lookup. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A rather simpler (but naive, and sometimes confusing) way to understand these lookup are these:&lt;br&gt;
LHS lookup is also called &lt;strong&gt;L&lt;/strong&gt;eft &lt;strong&gt;H&lt;/strong&gt;and &lt;strong&gt;S&lt;/strong&gt;ide lookup and RHS, &lt;strong&gt;R&lt;/strong&gt;ight &lt;strong&gt;H&lt;/strong&gt;and &lt;strong&gt;S&lt;/strong&gt;ide, because LHS happens for resolving identifier lookups on 'left-hand' of a statement (i.e while initialisation or re-initialisation) while RHS happens when identifiers are on the right-hand side (when we actually use that variable).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now that we have discussed lookups, let us talk about &lt;em&gt;Scope Chains&lt;/em&gt;. We established that in creation phase, JavaScript compiler creates lexical environments, which are just a static representation of scope. &lt;br&gt;
While creating lexical environments, the compiler associates different lexical environments with each other using the &lt;code&gt;outer&lt;/code&gt; variable.&lt;br&gt;
This association is based on nesting structure of code-blocks in the code-structure. For eg. &lt;code&gt;foo&lt;/code&gt;'s lexical environment will have an &lt;code&gt;outer&lt;/code&gt; variable pointing to the Global Lexical Environment. Similarly, the &lt;code&gt;if&lt;/code&gt;'s lexical environment's &lt;code&gt;outer&lt;/code&gt; variable will point to &lt;code&gt;foo&lt;/code&gt;'s lexical environment. We will now complete our diagram by filling the value of &lt;code&gt;outer&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--kpKGY6XG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7s3bg55npwngmgbjpw5h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--kpKGY6XG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7s3bg55npwngmgbjpw5h.png" alt="JavaScript Scopes with Example Code" width="800" height="577"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This association of lexical environments (or scopes) help JavaScript interpreter travel through different scopes when a lookup is not successful in the current scope using the &lt;code&gt;outer&lt;/code&gt; reference.&lt;/p&gt;

&lt;p&gt;For example, in our sample code, if we run call &lt;code&gt;foo(c)&lt;/code&gt;,&lt;br&gt;
when the interpreter reaches &lt;code&gt;console.log(b, d)&lt;/code&gt;, it tries to resolve for &lt;code&gt;d&lt;/code&gt; in the &lt;code&gt;if&lt;/code&gt;'s block scope. The lookup returns unsuccessful because &lt;code&gt;d&lt;/code&gt; is not defined there. It will then try to look into outer lexical environment using the &lt;code&gt;outer&lt;/code&gt; field of &lt;code&gt;if&lt;/code&gt;'s lexical environment, which is pointing to &lt;code&gt;foo&lt;/code&gt;'s lexical environment, because &lt;code&gt;if&lt;/code&gt; block is nested inside &lt;code&gt;foo&lt;/code&gt;. It finds it there and returns with a successful lookup.&lt;/p&gt;

&lt;p&gt;Hence, &lt;em&gt;scope chaining&lt;/em&gt; refers to a concept which represent accessible nested scopes of a JavaScript program as a result of writing lexically scoped code, which is utilised to resolve identifiers in a foreign scope, if the identifier is not resolved in the current scope.&lt;/p&gt;
&lt;h2&gt;
  
  
  Shadowing
&lt;/h2&gt;

&lt;p&gt;Shadowing refers to an event where the JavaScript engine resolves the value of a locally scoped identifier with same name as identifier in a foreign or outer scope. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;message&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Hello Global!&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;printMessage&lt;/span&gt;&lt;span class="p"&gt;(){&lt;/span&gt;
  &lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;message&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Hello Local!&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;printMessage&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// Hello Local!&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;message&lt;/code&gt; local to the scope of &lt;code&gt;printMessage&lt;/code&gt; function has said to have shadowed &lt;code&gt;message&lt;/code&gt; in global scope.&lt;/p&gt;

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

&lt;p&gt;Lexical environments, scopes and execution contexts advocate similar ideas at different time-period of the program. There is no such term as &lt;em&gt;Scope&lt;/em&gt; in ECMA specification. Scope is a passed around term generally meant for visibility of the identifier inside a code-block. However lexical environments and execution contexts are specification types. In a very generic sense, lexical environments are static representation of scope, while execution contexts are runtime representation of scope.&lt;/p&gt;

&lt;p&gt;Until next time, happy hacking :)&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>interview</category>
      <category>softwareengineering</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>JavaScript Runtime and Code Lifecycle</title>
      <dc:creator>Aditya Tripathi</dc:creator>
      <pubDate>Thu, 17 Aug 2023 09:10:44 +0000</pubDate>
      <link>https://dev.to/odus_ex/javascript-runtime-and-code-lifecycle-8dn</link>
      <guid>https://dev.to/odus_ex/javascript-runtime-and-code-lifecycle-8dn</guid>
      <description>&lt;p&gt;In this article we will explore all the important aspects of JavaScript's runtime. Our aim is to understand the general inner workings of JavaScript's runtime, covering all the important details. Let's delve in!&lt;/p&gt;

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

&lt;h2&gt;
  
  
  Architecture Overview
&lt;/h2&gt;

&lt;p&gt;JavaScript is a dynamic, single-threaded, JIT compiled, stack-oriented programming language. I have covered technical details of the language, in my other article: &lt;a href="https://dev.to/odus_ex/a-short-technical-introduction-to-javascript-13a0"&gt;Technical introduction to JavaScript&lt;/a&gt;. It is important to understand these aspects beforehand to get the most of this article.&lt;/p&gt;

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

&lt;p&gt;Lets start with a general architectural diagram of the browser runtime:&lt;/p&gt;

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

&lt;p&gt;In the above diagram, the colourful part is the core JavaScript. Everything else is the environment which is responsible to provide a platform to run JavaScript code successfully. &lt;/p&gt;

&lt;p&gt;Anytime we are running a JavaScript code, we are running it in some kind of environment, which is not a part of the language specification. A JavaScript Environment is a system that facilitates JavaScript code execution using an &lt;strong&gt;&lt;em&gt;engine&lt;/em&gt;&lt;/strong&gt; and extends JavaScript's functionality by providing different functions and APIs. For eg:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;NodeJS&lt;/em&gt; is a JavaScript environment which use a JavaScript engine called &lt;strong&gt;&lt;em&gt;V8&lt;/em&gt;&lt;/strong&gt; and provide APIs to create HTTP servers, handle file management and much more. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;Chromium&lt;/em&gt; based browsers (like &lt;em&gt;Google Chrome&lt;/em&gt;) are JavaScript environments which use V8 engine, same as &lt;em&gt;NodeJS&lt;/em&gt;, and provide Web APIs (&lt;code&gt;document&lt;/code&gt;, &lt;code&gt;window&lt;/code&gt;, etc) to perform front-end specific task for creating powerful dynamic websites.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Other famous browsers have their own implementations of Web APIs and engines. For eg. &lt;em&gt;Microsoft's Edge&lt;/em&gt; uses &lt;em&gt;Chakra&lt;/em&gt;, &lt;em&gt;Mozilla's Firefox&lt;/em&gt; uses &lt;em&gt;SpiderMonkey&lt;/em&gt;, etc.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Some IoT platforms use &lt;a href="https://duktape.org/" rel="noopener noreferrer"&gt;Duktape&lt;/a&gt; and &lt;a href="https://jerryscript.net/" rel="noopener noreferrer"&gt;JerryScript&lt;/a&gt; as their engines.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  JavaScript Code Execution
&lt;/h2&gt;

&lt;p&gt;JavaScript is a single-threaded language, which means it can only execute one task at a time. When a program is executed, the function being executed are called one by one for the execution. To keep track of the execution status and function calls, JavaScript utilise a stack data-structure called call-stack. To understand it better, lets consider an example:&lt;/p&gt;

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


&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;multiply&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;x&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="nx"&gt;y&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;x&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="nx"&gt;y&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;square&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;n&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;multiply&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;n&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;square&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;



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

&lt;/div&gt;

&lt;p&gt;When the above code is run, each function call pushes the function &lt;em&gt;being called&lt;/em&gt; into the call-stack. When the function has completed its execution, they are popped from the call-stack.&lt;/p&gt;

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

&lt;p&gt;The above code is executed synchronously, meaning all the execution happens immediately, in one go, at a given point of time, without the control shifting over to some other entity. To contrast, lets modify our example to understand asynchronous code behaviour.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;We can develop asynchronous code using JavaScript because of the &lt;strong&gt;&lt;em&gt;Event Loop&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;Call-back Queue&lt;/em&gt;&lt;/strong&gt;, provided by the runtime environment (see the architecture diagram above).  These features provided by JavaScript runtimes enable use to write asynchronous code. JavaScript by itself is a blocking synchronous language.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In the code below, we use a function from Web APIs called &lt;code&gt;setTimeout&lt;/code&gt; to create asynchronous behaviour. It enables us to call a function (passed as first parameter to &lt;code&gt;setTimeout&lt;/code&gt;) after a mentioned time in milliseconds (second parameter) hence making the code asynchronous.&lt;/p&gt;

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

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;multiply&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;x&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="nx"&gt;y&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;x&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="nx"&gt;y&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;square&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;n&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;multiply&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;n&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;n&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nf"&gt;setTimeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;later&lt;/span&gt;&lt;span class="p"&gt;(){&lt;/span&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;square&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;))},&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Hi&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;



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

&lt;/div&gt;

&lt;p&gt;Upon execution, the function &lt;code&gt;later&lt;/code&gt; is send to the call-back queue, to &lt;strong&gt;&lt;em&gt;call it back&lt;/em&gt;&lt;/strong&gt; after &lt;code&gt;1000&lt;/code&gt; milliseconds, or one second. That is why, when we run the code, we first see &lt;code&gt;Hi&lt;/code&gt; and then, at least after a second, &lt;code&gt;100&lt;/code&gt; in the output. When the code is getting interpreted, the asynchronous functions are send to the callback queue. These are pushed to stack once the call-stack is empty, this is done by &lt;strong&gt;&lt;em&gt;Event Loop&lt;/em&gt;&lt;/strong&gt;. &lt;/p&gt;

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

&lt;p&gt;By now we have a general idea of how JavaScript runtime works in synchronous and asynchronous operations. If you are interested in further explorations &lt;a href="https://www.jsv9000.app/" rel="noopener noreferrer"&gt;JS 900&lt;/a&gt; is a great tool to explore synchronous and asynchronous language behaviour in-depth. &lt;/p&gt;

&lt;p&gt; &lt;br&gt;
 &lt;/p&gt;

&lt;h2&gt;
  
  
  JavaScript Code Lifecycle
&lt;/h2&gt;

&lt;p&gt;Let us go one level deeper in understanding how the code being executed is transformed end-to-end i.e. starting from source file all the way to generating machine code and executing it.&lt;/p&gt;

&lt;p&gt;When we run a JS program in any environment discussed above, it goes to different phases before it is finally executed. These are namely &lt;em&gt;Tokenisation&lt;/em&gt;, &lt;em&gt;Parsing&lt;/em&gt;, &lt;em&gt;Code-Generation&lt;/em&gt; and finally &lt;em&gt;Code-Execution&lt;/em&gt;. &lt;/p&gt;

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

&lt;blockquote&gt;
&lt;p&gt;Novice developers often claim that JavaScript is an interpreted language, but as we will see below, this is only half-truth.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Any JavaScript program is always tokenised and parsed to generate an intermediate form of code called &lt;em&gt;byte-code&lt;/em&gt; which is then interpreted by an &lt;em&gt;Interpreter&lt;/em&gt; to generate executable &lt;em&gt;machine code&lt;/em&gt;. This is different from purely interpreted languages where source code is directly converted to machine code for execution. (&lt;a href="https://www.geeksforgeeks.org/difference-between-byte-code-and-machine-code/" rel="noopener noreferrer"&gt;Difference between Byte Code and Machine Code&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;A JavaScript program is dynamically compiled to byte-code, before it is interpreted and executed. This is why JavaScript is a 'Just-in-time' (JIT) compiled language. Notice that we used the term &lt;em&gt;dynamically&lt;/em&gt; compiled. This is to reflect on the fact that JavaScript Engine doesn't have the luxury to pre-compile JavaScript and run it later (also called &lt;em&gt;static&lt;/em&gt; compilation or &lt;em&gt;Ahead-of-Time&lt;/em&gt; (AOT) compilation) like other compiled languages. Lets understand this whole jargon step-by-step in detail now. To set the premise, the JavaScript runtime under consideration is V8, used by Chromium based browsers and NodeJS.&lt;/p&gt;

&lt;p&gt;We start with a sample JavaScript source code.&lt;/p&gt;

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

&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;sayHello&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Hello World!&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;printMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;message&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nf"&gt;printMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;sayHello&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


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

&lt;/div&gt;

&lt;p&gt;The engine starts with locating the source code. Generally, this code will either be on a file, in a Web Server or present in a script embedded in an HTML &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; tag. &lt;/p&gt;

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

&lt;h3&gt;
  
  
  Tokenisation
&lt;/h3&gt;

&lt;p&gt;After identification, the source code is tokenised. The process is called &lt;strong&gt;&lt;em&gt;tokenisation&lt;/em&gt;&lt;/strong&gt;. During the process, JavaScript engine converts syntactically sound source code into &lt;em&gt;tokens&lt;/em&gt;. This is the process where error in syntax are highlighted. In very simple terms, the source code is broken down into smaller valid language constructs. For eg. &lt;code&gt;var sayHello = 'Hello World!';&lt;/code&gt; is broken down into &lt;code&gt;var&lt;/code&gt; a keyword to declare functional scope variables, &lt;code&gt;sayHello&lt;/code&gt; an identifier, &lt;code&gt;=&lt;/code&gt; an operator and &lt;code&gt;'Hello World'&lt;/code&gt; a string literal and finally &lt;code&gt;;&lt;/code&gt; a punctuator.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In some compiled languages, this process is also called &lt;em&gt;lexing&lt;/em&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

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

&lt;h3&gt;
  
  
  Parsing
&lt;/h3&gt;

&lt;p&gt;Once the tokens are generated, they are passed to a &lt;strong&gt;&lt;em&gt;Parser&lt;/em&gt;&lt;/strong&gt; as input, which performs &lt;em&gt;parsing&lt;/em&gt;. Parsing is the process to generate Abstract Syntax Tree (&lt;a href="https://en.wikipedia.org/wiki/Abstract_syntax_tree" rel="noopener noreferrer"&gt;AST&lt;/a&gt;) and execution scopes. Generating AST allow us to represent the hierarchal structure of the program. This hierarchy information is used by Interpreter in subsequent steps for generating byte-code.&lt;/p&gt;

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

&lt;p&gt;Notice that AST doesn't directly contain the value of the literals or variables. We will cover this later. &lt;/p&gt;

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

&lt;p&gt;For V8 engine, there are two types of parsing: &lt;em&gt;eager parsing&lt;/em&gt; and &lt;em&gt;lazy parsing&lt;/em&gt;. The eager parsing generates both AST and execution scopes, while lazy parsing only generates AST.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Execution scopes, in simple terms are places which map identifiers to their assigned value. For our example &lt;code&gt;a&lt;/code&gt; is mapped to &lt;code&gt;10&lt;/code&gt; number literal. This information is stored in execution scopes, instead of directly putting them in AST, to keep the AST generation a fast process. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Eager parsing is used for top level code, which will be executed immediately by the Interpreter while lazy parsing is for the nested code and declarations which are not called and hence are not required for the execution of the program yet.&lt;/p&gt;

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

&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;sayHello&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Hello World!&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// eagerly parsed&lt;/span&gt;

&lt;span class="c1"&gt;// eagerly parsed, but everything inside is lazy parsed for now&lt;/span&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;printMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;message&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt; 
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// oh shit, need to parse everything eagerly inside, as the function is called.&lt;/span&gt;
&lt;span class="nf"&gt;printMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;sayHello&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; 


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

&lt;/div&gt;

&lt;p&gt;In eager parsing, the generated execution scopes are used to assign identifier values to &lt;em&gt;variable proxies&lt;/em&gt; inside AST (as mentioned in the diagram above), which did not have any values assigned to them while AST generation. Lazy parsed AST are left without assigning the identifier values so that they are created faster and hence speed up the parsing process. The process of assigning identifier value from execution scopes to variable proxies in AST is referred to as &lt;em&gt;Scope Analysis&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Lazy parsing is performed by a &lt;em&gt;pre-parser&lt;/em&gt; according to the V8 terminology. Pre-parsers are twice as fast as Parsers because they skip execution scope generation and value assignments.&lt;/p&gt;
&lt;/blockquote&gt;

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

&lt;h3&gt;
  
  
  Code-Generation &amp;amp; Execution
&lt;/h3&gt;

&lt;p&gt;Once the AST is generated and hydrated (variables proxies assigned with values), it is passed to a &lt;em&gt;Byte-code Generator&lt;/em&gt;. It is responsible for producing a stream of byte-code, one byte-code at a time. Once the byte-code is generated, it is finally interpreted by an Interpreter to produce &lt;em&gt;machine Code&lt;/em&gt; (0s and 1s). The machine code is then executed to produce the program output.&lt;/p&gt;

&lt;p&gt; &lt;br&gt;
 &lt;/p&gt;

&lt;h3&gt;
  
  
  A word on Javascript Optimisations
&lt;/h3&gt;

&lt;p&gt;As a side note, it is a good option to discuss some techniques like &lt;em&gt;inline caching&lt;/em&gt; adopted by JavaScript engines to speed up the code compilation and execution process. JavaScript engines are capable of optimising code runs when a piece of code is being run multiple times.&lt;/p&gt;

&lt;p&gt;As we have already discussed above, once the hydrated AST is fed to an Interpreter, it starts generating a stream of byte-code. While it is doing this, the output stream is passed to an &lt;em&gt;'optimising compiler'&lt;/em&gt;  which is responsible for producing an optimised version of machine code, depending on what information it has from previous execution runs. Below is a very generic diagram of the process. The whole process is referred to as &lt;em&gt;execution &amp;amp; optimisation pipeline&lt;/em&gt;. &lt;/p&gt;

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

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

&lt;p&gt;When the Interpreter is generating byte-code, it also stores some sort of &lt;em&gt;profiling data&lt;/em&gt;, which can be used in subsequent runs. When a function becomes &lt;em&gt;'hot'&lt;/em&gt; (i.e. when it has been run multiple times), the byte-code generated for that function, along with the profiling data is passed to the optimising compiler to create &lt;em&gt;'inline cache'&lt;/em&gt; for that function, which on future runs, are directly swapped in the byte-code stream instead of regenerating the byte-code. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Some engines have multiple optimising compilers instead of just one. Essentially all optimisations and caching techniques function on the fact that JavaScript engine is able to &lt;em&gt;'profile'&lt;/em&gt; the &lt;em&gt;Object Shape&lt;/em&gt; (everything non-primitive in JavaScript is an Object). The article: &lt;a href="https://mathiasbynens.be/notes/shapes-ics" rel="noopener noreferrer"&gt;JavaScript Shapes and Inline Caches&lt;/a&gt; explains the whole optimisation process in detail.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt; &lt;br&gt;
 &lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;Our journey into JavaScript's runtime has unveiled its core mechanics, from architecture to code execution and lifecycle. We've grasped its dynamic, single-threaded nature, role of environments, and execution contexts. Understanding both synchronous and asynchronous code execution, the event loop's role, and diving into the lifecycle from source to machine code, we've unraveled JavaScript's essence as a "Just-in-time" compiled language. Further, optimisation techniques like inline caching have been explored, showcasing the intricate strategies boosting performance. &lt;/p&gt;

&lt;p&gt;Until next time :)&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>interview</category>
      <category>architecture</category>
      <category>webdev</category>
    </item>
    <item>
      <title>A technical introduction to JavaScript</title>
      <dc:creator>Aditya Tripathi</dc:creator>
      <pubDate>Sun, 30 Jul 2023 11:06:38 +0000</pubDate>
      <link>https://dev.to/odus_ex/a-short-technical-introduction-to-javascript-13a0</link>
      <guid>https://dev.to/odus_ex/a-short-technical-introduction-to-javascript-13a0</guid>
      <description>&lt;p&gt;In this article, my goal is to offer an easily understandable technical overview of the JavaScript language, tailored for entry-level developers. I will cover a range of general technical aspects of JavaScript, providing insights into its key concepts and features. Additionally, I will include plenty of helpful resources for readers to delve deeper into the language without the hassle of searching extensively for reliable articles.&lt;/p&gt;

&lt;h2&gt;
  
  
  TLDR;
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;JavaScript is a high-level, dynamic, single-threaded language which is stack-oriented and JIT compiled.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Abbreviated as JS, it was created in 1995 to introduce interactivity to static web pages.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;JavaScript adheres to the &lt;em&gt;ECMAScript&lt;/em&gt; standard, specified in the standard &lt;em&gt;ECMA-262&lt;/em&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;JavaScript consists of two types of constructs: &lt;em&gt;Primitives&lt;/em&gt; and &lt;em&gt;Non-Primitives&lt;/em&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;JavaScript is always &lt;em&gt;pass-by-value&lt;/em&gt; language and treats functions as &lt;em&gt;first-class citizens&lt;/em&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The utility of JavaScript's &lt;em&gt;Primitives&lt;/em&gt; can be extended through &lt;em&gt;Primitive Wrappers&lt;/em&gt;. This is achieved by invoking a &lt;em&gt;Constructor function&lt;/em&gt; with the primitive as its argument.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt; &lt;br&gt;
 &lt;/p&gt;
&lt;h2&gt;
  
  
  The high level intro
&lt;/h2&gt;

&lt;p&gt;JavaScript has been a foundational technology since the introduction of the &lt;em&gt;World Wide Web&lt;/em&gt;. It was created by &lt;a href="https://www.linkedin.com/in/brendaneich/" rel="noopener noreferrer"&gt;Brendan Eich&lt;/a&gt; in 1995. Over the years, JS has evolved significantly, transforming from a language that made static HTML content interactive to a powerful cornerstone of modern-day web applications.&lt;/p&gt;

&lt;p&gt;To appeal to developers at that time, JavaScript drew inspiration from languages like &lt;a href="https://en.wikipedia.org/wiki/C_(programming_language)" rel="noopener noreferrer"&gt;C&lt;/a&gt; and &lt;a href="https://en.wikipedia.org/wiki/Lisp_(programming_language)" rel="noopener noreferrer"&gt;Lisp&lt;/a&gt;. Apart from being a &lt;a href="https://en.wikipedia.org/wiki/High-level_programming_language" rel="noopener noreferrer"&gt;high-level&lt;/a&gt;, single-threaded language it is Just-In-Time compiled (&lt;a href="https://en.wikipedia.org/wiki/Just-in-time_compilation" rel="noopener noreferrer"&gt;JIT&lt;/a&gt;) and &lt;a href="https://stackoverflow.com/questions/1517582/what-is-the-difference-between-statically-typed-and-dynamically-typed-languages" rel="noopener noreferrer"&gt;dynamically typed&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt; &lt;br&gt;
 &lt;/p&gt;
&lt;h2&gt;
  
  
  The specification
&lt;/h2&gt;

&lt;p&gt;JavaScript conforms to a set of specification created and maintained by an organisation called European Computer Manufacturers Association, &lt;a href="https://www.ecma-international.org/" rel="noopener noreferrer"&gt;ECMA&lt;/a&gt;. Apart from creating computer language specifications, ECMA is involved in standardising various areas, such as multimedia communications and electronic equipment safety. Each specification they produce is assigned a reference number or a &lt;em&gt;code&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;The specification code followed by JavaScript is &lt;a href="https://www.ecma-international.org/publications-and-standards/standards/ecma-262/" rel="noopener noreferrer"&gt;ECMA-262&lt;/a&gt;. It defines a general-purpose, vendor-neutral scripting language called &lt;em&gt;ECMAScript&lt;/em&gt;. You can find the latest draft of the standard &lt;a href="https://tc39.es/ecma262/" rel="noopener noreferrer"&gt;here&lt;/a&gt;. In essence, ECMAScript serves as the blueprint for JavaScript. &lt;/p&gt;

&lt;p&gt;So, if someone mentions that ECMAScript is the same as JavaScript, correct them:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;ECMAScript refers to the standard described in the &lt;em&gt;ECMA-262&lt;/em&gt; specification. JavaScript is a language that conforms to this standard, with some variations, which we will discuss below.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For more detailed information on the relationship between ECMAScript and JavaScript evolution, you can read &lt;a href="https://medium.com/@m_sally/what-is-ecmascript-and-javascript-relation-c419d6a6fb36" rel="noopener noreferrer"&gt;this article&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Before discussing the variations, let's mention an important group called &lt;em&gt;TC39&lt;/em&gt;, which is part of &lt;em&gt;ECMA&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://tc39.es/" rel="noopener noreferrer"&gt;TC39&lt;/a&gt; is a group of developers and academics which is responsible for understanding the specification and evolving JavaScript, conforming to the sepcification. If you had trouble with different versions of JavaScript like ES6, ES5, ES3 etc, you now know who to blame. &lt;/p&gt;

&lt;p&gt;Regarding variations from the specification, JavaScript incorporates a handful of features not mentioned in &lt;em&gt;ECMA-262&lt;/em&gt;  (like &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" rel="noopener noreferrer"&gt;ArrayBuffers&lt;/a&gt;). These intricate details further differentiate ECMAScript from JavaScript.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/xkmNi280NkrcY/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/xkmNi280NkrcY/giphy.gif" alt="confused and stressed"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;That covers the general overview about specifications. Now, let's delve into some implementation details of the language.&lt;/p&gt;

&lt;p&gt; &lt;br&gt;
 &lt;/p&gt;
&lt;h2&gt;
  
  
  JavaScript General Characteristics
&lt;/h2&gt;

&lt;p&gt;Before starting development with JavaScript, it's essential to understand its general characteristics.&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;
&lt;h3&gt;
  
  
  Primitives, Non-Primitives and Primitive Wrappers
&lt;/h3&gt;

&lt;p&gt;In JavaScript, everything is categorised as either a &lt;em&gt;Primitive&lt;/em&gt; type or a &lt;em&gt;Non-Primitive&lt;/em&gt; type (i.e. &lt;em&gt;Objects&lt;/em&gt;).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive" rel="noopener noreferrer"&gt;Primitives&lt;/a&gt; are immutable and single valued. &lt;/li&gt;
&lt;li&gt;Non-Primitives, on the other hand, are &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" rel="noopener noreferrer"&gt;objects&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;There are seven primitive types in the language: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;number&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;bigInt&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;string&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;boolean&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;null&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;undefined&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Symbol&lt;/code&gt; &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;On the other hand, constructs like functions and arrays are a special type of object and hence are classified as Non-Primitves. It is safe to assume that any language construct that is not a Primitive is classified as an object. &lt;/p&gt;
&lt;h3&gt;
  
  
  Constructors and Primitive Wrappers
&lt;/h3&gt;

&lt;p&gt;While working with JavaScript, you might come across built-in constructor functions that resemble the names of Primitives. These are: &lt;code&gt;String()&lt;/code&gt;, &lt;code&gt;Number()&lt;/code&gt; and &lt;code&gt;Boolean()&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;aString&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;What am I?&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;aStringObject&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;aString&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;typeof&lt;/span&gt; &lt;span class="nx"&gt;aString&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;  &lt;span class="c1"&gt;//string&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;typeof&lt;/span&gt; &lt;span class="nx"&gt;aStringObject&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;  &lt;span class="c1"&gt;//object&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;The motivation behind having a constructor function for primitive values is to extend the functionality of a primitive. Primitives are single immutable values, while non-primitives are objects, so they can have different attributes and functions assigned to them. This feature allows us to add utility to a primitive, essentially extending its ability. &lt;/p&gt;

&lt;p&gt;In the example above, when we use a constructor function on a primitive, it enables us to use certain methods on the value defined in the &lt;code&gt;String&lt;/code&gt; object. The constructor function (&lt;code&gt;String()&lt;/code&gt;) wraps the primitive into a &lt;code&gt;String&lt;/code&gt; object, becoming a &lt;em&gt;Primitive Wrapper&lt;/em&gt;. This object contains functions like &lt;code&gt;toUpperCase()&lt;/code&gt;, &lt;code&gt;toLowerCase()&lt;/code&gt;, &lt;code&gt;charAt()&lt;/code&gt;, etc., which can now be used on the wrapped primitive value directly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;aStringObject&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toUpperCase&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// WHAT AM I?&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Meanwhile, you may also notice that we can use methods available in the &lt;code&gt;String&lt;/code&gt; object on a primitive value without explicitly wrapping it in a Constructor, as shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;
&lt;span class="nx"&gt;aString&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toLowerCase&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="c1"&gt;// what am i?&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;This is because JavaScript implicitly wraps the &lt;code&gt;String&lt;/code&gt; object whenever it notices that we are trying to access one of the functions present in the Wrapper. This process of automatic implicit type conversion is called Coercion. You can explore more about it &lt;a href="https://www.freecodecamp.org/news/coercion-and-type-conversion-in-javascript/" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

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

&lt;h3&gt;
  
  
  Function as first class citizen
&lt;/h3&gt;

&lt;p&gt;The concept of first-class and second-class citizens originated with &lt;a href="https://en.wikipedia.org/wiki/ALGOL" rel="noopener noreferrer"&gt;Algol&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Although not strictly defined at that time, a first-class citizen is generally something that supports all types of available operations on itself. This includes being passed as arguments, returned from a function, and assigned to a variable.&lt;/p&gt;

&lt;p&gt;In JavaScript function behave as first-class citizens because all the functions are a variation of JavaScript objects, which as we have studied are building blocks of the language along with &lt;em&gt;Primitives&lt;/em&gt;. Learn more about first-class functions &lt;a href="https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt; &lt;br&gt;
 &lt;/p&gt;

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

&lt;p&gt;When we execute JavaScript code, it goes through a runtime process involving several entities. To understand the end-to-end execution process, we'll take a top-down approach to break it down step-by-step. This means we start from a  file with &lt;strong&gt;.js&lt;/strong&gt; extension containing some JavaScript code.&lt;/p&gt;

&lt;p&gt;The JavaScript code is executed as follows, steps ordered chronologically:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Identifying the source code&lt;/strong&gt;
The runtime identifies the source code in the &lt;strong&gt;.js&lt;/strong&gt; file. For simplicity, we assume there are no syntactical errors in the source code.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Tokenization (Lexing)&lt;/strong&gt;
The source code is tokenized, a process known as &lt;em&gt;tokenization&lt;/em&gt; or &lt;em&gt;lexing&lt;/em&gt;. This breaks the code into smaller units called tokens.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Abstract Syntax Tree Generation&lt;/strong&gt;
The tokenized code is used to generate the Abstract Syntax Tree (&lt;a href="https://en.wikipedia.org/wiki/Abstract_syntax_tree" rel="noopener noreferrer"&gt;AST&lt;/a&gt;) which represents the structure of the code. This process is called as &lt;em&gt;parsing&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Code Generation&lt;/strong&gt;
The generated AST is used to create executables, sometimes referred to as &lt;em&gt;byte-code&lt;/em&gt;. This step is known as &lt;em&gt;code generation&lt;/em&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;This is just a high level explanation of the JavaScript code lifecycle. For in-depth exploration, checkout &lt;a href="https://medium.com/jspoint/how-javascript-works-in-browser-and-node-ab7d0d09ac2f" rel="noopener noreferrer"&gt;this&lt;/a&gt; article, after you have read the overview. It will take you to the abyss.  &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Finally, the byte-code is translated into machine code, with platform-dependent optimisations, and executed to produce the required results.&lt;/p&gt;

&lt;p&gt;The following picture summarises the process:&lt;/p&gt;

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

&lt;p&gt; &lt;br&gt;
 &lt;/p&gt;

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

&lt;p&gt;In this article, I have covered essential topics that provide a strong technical foundation for those who are new to learning the JavaScript language. If you're starting to learn JavaScript, these topics will give you a better perspective on the language.&lt;/p&gt;

&lt;p&gt;For more insights into JavaScript technicalities, I highly recommend checking out &lt;a href="https://betterprogramming.pub/an-intro-to-javascript-for-experienced-programmers-who-could-use-a-strong-dose-of-fundamentals-31535030616b" rel="noopener noreferrer"&gt;this resource&lt;/a&gt; beautifully summarised by &lt;a href="https://www.linkedin.com/in/tonystubblebine/" rel="noopener noreferrer"&gt;Tony Stubblebine&lt;/a&gt; which served as my inspiration for writing this article.  I've made sure that the content of both articles is unique to offer the readers the most value.&lt;/p&gt;

&lt;p&gt;Thank you for taking the time to read my article! I would greatly appreciate your suggestions and feedback in the comments below, as it will help me further improve the content for the readers.&lt;/p&gt;

&lt;p&gt;Happy Coding! &lt;/p&gt;

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