<?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: Aiman Jaffer</title>
    <description>The latest articles on DEV Community by Aiman Jaffer (@aimanjaffer).</description>
    <link>https://dev.to/aimanjaffer</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%2F620588%2F241082bc-22b7-493a-9a0e-41e2104c818d.jpeg</url>
      <title>DEV Community: Aiman Jaffer</title>
      <link>https://dev.to/aimanjaffer</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/aimanjaffer"/>
    <language>en</language>
    <item>
      <title>React Internals: How React works</title>
      <dc:creator>Aiman Jaffer</dc:creator>
      <pubDate>Mon, 18 Oct 2021 18:25:35 +0000</pubDate>
      <link>https://dev.to/aimanjaffer/react-internals-class-components-vs-functional-components-virtual-dom-fibers-reconciliation-and-rendering-process-340a</link>
      <guid>https://dev.to/aimanjaffer/react-internals-class-components-vs-functional-components-virtual-dom-fibers-reconciliation-and-rendering-process-340a</guid>
      <description>&lt;p&gt;This article will attempt to formalize my understanding of how the React library work internally to allow us to create complex web-applications. Without any further ado, let's dive right into it.&lt;/p&gt;




&lt;h2&gt;
  
  
  HTML and the DOM
&lt;/h2&gt;

&lt;p&gt;Let's start with two terms that you will encounter a lot in web development: HTML and DOM. HTML stands for Hypertext Markup Language. A web-page is simply a document written in HTML.&lt;/p&gt;

&lt;p&gt;DOM stands for Document Object Model. The DOM is the representation of the web-page that is understood by the web-browser. The DOM is represented as a tree of HTML tags. (In a Tree data structure, each node can have zero or more child-nodes. The child-nodes belonging to the same parent are known as siblings and nodes without children are known as leaf nodes.)&lt;/p&gt;

&lt;p&gt;The DOM provides APIs through which we can make changes to the web-page. For example using methods like &lt;code&gt;document.getElementById&lt;/code&gt; etc.&lt;/p&gt;




&lt;h2&gt;
  
  
  Components
&lt;/h2&gt;

&lt;p&gt;React is a Component-based library. Components are a layer of abstraction in that they allow us to describe the UI we wish to generate while leaving the implementation details to React.&lt;br&gt;
React Components can be created in two ways:&lt;br&gt;
1) Using Classes&lt;br&gt;
2) Using Functions&lt;/p&gt;

&lt;p&gt;While using Class-based components we use the &lt;code&gt;render()&lt;/code&gt; method to define the JSX that should be displayed on the browser whereas while using Functional components we directly &lt;code&gt;return&lt;/code&gt; the JSX that should be rendered as the result of the function.&lt;/p&gt;


&lt;h2&gt;
  
  
  JSX and React.createElement
&lt;/h2&gt;

&lt;p&gt;JSX allows you to write HTML code directly inside JavaScript functions. It is syntactic sugar for the method &lt;code&gt;React.createElement()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;JSX is converted to regular JavaScript via a transpiler known as Babel (using the preset babel/preset-react).&lt;/p&gt;

&lt;p&gt;Let's examine this in detail using an example:&lt;br&gt;
This is a simple Component that I already had from a hobby project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;PlaylistDetail&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;props&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="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;div&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;p&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;Playlist Name&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;p&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;p&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;Created by&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;p&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;div&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;Track List&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;div&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;div&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&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;Compiling this code using Babel produces the following output:&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="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;use strict&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nb"&gt;Object&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;defineProperty&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;exports&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;__esModule&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;span class="nx"&gt;exports&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;default&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;PlaylistDetail&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;PlaylistDetail&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;props&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="cm"&gt;/*#__PURE__*/&lt;/span&gt; &lt;span class="nx"&gt;React&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;createElement&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;div&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="cm"&gt;/*#__PURE__*/&lt;/span&gt; &lt;span class="nx"&gt;React&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;createElement&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;p&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Playlist Name&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
    &lt;span class="cm"&gt;/*#__PURE__*/&lt;/span&gt; &lt;span class="nx"&gt;React&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;createElement&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;p&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Created by&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
    &lt;span class="cm"&gt;/*#__PURE__*/&lt;/span&gt; &lt;span class="nx"&gt;React&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;createElement&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;div&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Track List&lt;/span&gt;&lt;span class="dl"&gt;"&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;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From this, we conclude that JSX tags are ultimately converted to calls to the &lt;code&gt;React.createElement()&lt;/code&gt; method. Now you may be thinking: That's great! But why should I care? We'll get to that in a bit. Hang tight, all of this will make a lot more sense in a bit, I promise. We just need to understand what an Element is in React.&lt;/p&gt;




&lt;h2&gt;
  
  
  Elements and Component Instances
&lt;/h2&gt;

&lt;p&gt;An Element in React is a simple JavaScript object that describes the &lt;em&gt;instance of a component&lt;/em&gt;. Think of Components as being general and Component instances as specific (i.e. A Component with specific props and state). Whenever the props and state of a Component change it results in a different instance of the Component.&lt;/p&gt;

&lt;p&gt;The Element object representing the instance of the PlaylistDetail Component seen previously is 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="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;$$typeof&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Symbol&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;react&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;element&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
  &lt;span class="nx"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;props&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nl"&gt;children&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="nx"&gt;$&lt;/span&gt;&lt;span class="na"&gt;$typeof&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Symbol&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;react&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;element&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
        &lt;span class="na"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;props&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
          &lt;span class="na"&gt;children&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Playlist Name&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="na"&gt;ref&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;p&lt;/span&gt;&lt;span class="dl"&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;$&lt;/span&gt;&lt;span class="na"&gt;$typeof&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Symbol&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;react&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;element&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
        &lt;span class="na"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;props&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
          &lt;span class="na"&gt;children&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Created by&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="na"&gt;ref&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;p&lt;/span&gt;&lt;span class="dl"&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;$&lt;/span&gt;&lt;span class="na"&gt;$typeof&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Symbol&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;react&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;element&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
        &lt;span class="na"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;props&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
          &lt;span class="na"&gt;children&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Track List&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="na"&gt;ref&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;div&lt;/span&gt;&lt;span class="dl"&gt;"&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="nx"&gt;ref&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;div&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;The &lt;code&gt;$$typeof&lt;/code&gt; field is used to prevent Cross site scripting Attacks (XSS) since it should always contain a &lt;code&gt;Symbol&lt;/code&gt; which prevents the JavaScript object from being parsed from plain JSON objects.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;key&lt;/code&gt; field is used to optimize performance by allowing elements generated from a list to be uniquely identified.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;props&lt;/code&gt; field is an object containing all the props that are passed to the Component. The &lt;code&gt;props&lt;/code&gt; field also stores &lt;code&gt;children&lt;/code&gt; which is an array containing the children of the current element.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;type&lt;/code&gt; field refers to the type of the object either a native HTML tag or a Component type. In this example the type is a native HTML div.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;ref&lt;/code&gt; field stores a reference to the actual DOM node. (This can be utilized via the &lt;code&gt;useRef&lt;/code&gt; hook).&lt;/p&gt;

&lt;p&gt;Thus, we see that React components (and their child components) can be represented as objects (with nested objects) similar to the way the web-page is itself represented via the tree structure of the DOM. Hence this representation of React components as a tree of objects is known as the &lt;strong&gt;Virtual DOM&lt;/strong&gt;.&lt;/p&gt;




&lt;h2&gt;
  
  
  Why bother?
&lt;/h2&gt;

&lt;p&gt;The reason React goes through this cumbersome process of maintaining object representations of Components is simple: &lt;strong&gt;Performance&lt;/strong&gt;. &lt;em&gt;It's computationally much cheaper to create and manipulate JavaScript objects than it is to manipulate the DOM.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This allows React to consolidate all the changes that need to be made in a render cycle and perform one bulk update to the DOM instead of performing many smaller changes.&lt;/p&gt;




&lt;h2&gt;
  
  
  Reconciliation
&lt;/h2&gt;

&lt;p&gt;Now, let's take a look at how React determines when a Component needs to be re-rendered and what exactly has changed since the previous render cycle. This information is required in order to prevent unnecessary DOM updates. (i.e. updating DOM nodes that have not been changed since the previous render) &lt;/p&gt;

&lt;p&gt;The process of maintaining the tree of Elements whenever a Component's props or state change is known as &lt;strong&gt;Reconciliation&lt;/strong&gt;. React does this by maintaining the state of the Element tree from the previous render and comparing it to the new Element tree using an &lt;strong&gt;diffing algorithm&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The problem of comparing the previous tree (or graph) with the new tree is known in Computer Science as the &lt;a href="https://en.wikipedia.org/wiki/Graph_edit_distance"&gt;&lt;strong&gt;Graph Edit Distance Problem&lt;/strong&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Theoretically, this problem falls under a class of problems known as &lt;em&gt;NP-hard&lt;/em&gt; (non-deterministic polynomial-time) but there are approximation solutions to this problem in O(n^3). React's diffing algorithm uses certain optimizations that further reduce the runtime to &lt;strong&gt;O(n)&lt;/strong&gt;. (n is number of nodes in the tree).&lt;/p&gt;




&lt;h2&gt;
  
  
  Optimizations, you say?
&lt;/h2&gt;

&lt;p&gt;The optimizations React uses to achieve this performance boost are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;If an element's &lt;code&gt;type&lt;/code&gt; field has changed, then React re-creates the entire subtree (for this particular element and it's children).&lt;/li&gt;
&lt;li&gt;React uses the &lt;code&gt;key&lt;/code&gt; field to uniquely identify elements generated dynamically from a list in order to prevent recreating the entire list when list operations are performed (E.g. when elements added or deleted, or list is reversed etc.). React simply makes the relevant changes directly in the DOM.&lt;/li&gt;
&lt;li&gt;When attributes of native DOM elements are changed but the element type remains the same then only the attributes that have changed are updated (instead of re-creating the entire DOM Node).&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  Rendering vs Reconciliation
&lt;/h2&gt;

&lt;p&gt;The process of Reconciliation (that we looked at in the previous section) determines what changes need to be made to the DOM.&lt;/p&gt;

&lt;p&gt;The process of actually making these changes is known as &lt;strong&gt;Rendering&lt;/strong&gt;. There is a separation of concerns between the packages responsible for Reconciliation and Rendering.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;react&lt;/code&gt; package is only concerned wit Reconciliation.&lt;br&gt;
The &lt;code&gt;react-dom&lt;/code&gt; package is concerned with actually performing the rendering on the browser. It does this via the &lt;code&gt;ReactDOM.render()&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;This separation of concerns allows &lt;code&gt;react-native&lt;/code&gt; to replace &lt;code&gt;react-dom&lt;/code&gt; while rendering to mobile apps. &lt;/p&gt;




&lt;p&gt;TO BE CONTINUED&lt;/p&gt;

&lt;h2&gt;
  
  
  How does Rendering work? Fibers
&lt;/h2&gt;

&lt;h2&gt;
  
  
  How Rendering previously worked with React Stack? (before v16) Stack vs LinkedList
&lt;/h2&gt;

</description>
    </item>
    <item>
      <title>Lessons Learnt: Building a real-time direct messaging web app</title>
      <dc:creator>Aiman Jaffer</dc:creator>
      <pubDate>Mon, 04 Oct 2021 20:46:01 +0000</pubDate>
      <link>https://dev.to/aimanjaffer/lessons-learnt-building-a-real-time-direct-messaging-web-app-2bhe</link>
      <guid>https://dev.to/aimanjaffer/lessons-learnt-building-a-real-time-direct-messaging-web-app-2bhe</guid>
      <description>&lt;p&gt;I recently worked on building two personal projects that involve real-time communication between users. The first was a direct messaging application and the second was an online chess application. These are my key takeaways and lessons learnt from the process of building these two applications. Let's begin by taking a look at the architecture of these applications individually.&lt;/p&gt;

&lt;h2&gt;
  
  
  Application Overview
&lt;/h2&gt;

&lt;p&gt;This was the first real-time web application that I was involved in building. I had recently learnt React.js and I was eager for an opportunity to put my theoretical knowledge to test and to prove to myself that I was in fact capable of developing responsive React applications.&lt;/p&gt;

&lt;p&gt;I had chosen the MERN stack for this project since since it seemed like the go-to option to use a Javascript backend (Node.js + Express) alongside a React frontend. I had also never used a NoSQL database before, all my database experience was with relational databases so I was keen to give it a shot with nothing at stake but my self-esteem.&lt;/p&gt;

&lt;p&gt;I knew that one of the most important things for a good user experience when using any messenger application is that messages should automatically show up on the conversation screen without the user having to refresh their browser window each time. I did a bit of Googling and decided that this would be a good use case for WebSockets.&lt;/p&gt;

&lt;h2&gt;
  
  
  User Stories
&lt;/h2&gt;

&lt;p&gt;I decided that the Minimum Viable Product for this build should incorporate at least the following user stories:&lt;br&gt;
1) Users should be able to sign-up using a username + password.&lt;br&gt;
2) Users should be able to login using their credentials.&lt;br&gt;
3) After successful login, Users should see a list of their ongoing conversations on the left pane.&lt;br&gt;
3) Users should be able to start a new conversation using the "New Chat" button. &lt;br&gt;
4) On clicking a conversation summary, the entire conversation should load on the right pane.&lt;br&gt;
5) Users should be able to receive notifications when they receive a new message.&lt;br&gt;
6) Users should be able to send messages. (I'll admit, this one was not that hard to think of)&lt;/p&gt;

&lt;p&gt;I estimated that it would take about a week to complete if I was able to dedicate at least 2-3 hours per night. Furthermore, I wasn't too concerned about designing a beautiful User Interface (&lt;strong&gt;this was my first mistake&lt;/strong&gt;) so I decided that Bootstrap was good enough for the task at hand. If I could do it all over again I would undoubtedly use TailwindCSS since their utility first approach (as opposed to Bootstrap's component first approach) leads to much more unique looking webpages. It's relatively trivial to instantly know when a web-app uses Bootstrap because all of them are practically identical, which is not the case with web-apps that use utility-based frameworks like Tailwind.&lt;/p&gt;

&lt;h2&gt;
  
  
  UI Components
&lt;/h2&gt;

&lt;p&gt;The next step were to determine the UI components that I would need. These were the components that I ultimately decided on.&lt;/p&gt;

&lt;p&gt;LoginComponent: Form where the User submits their username.&lt;br&gt;
HomeComponent: Parent Component for all these components listed below.&lt;br&gt;
ConversationSummaryList: Displayed after successful login, shows all the conversations the user has had.&lt;br&gt;
ConversationSummary: Displays Conversation Name, Last Message. When clicked loads the respective Conversation component in the right pane&lt;br&gt;
NewConversation: Button that when clicked loads ContactList &lt;br&gt;
ContactList: List that displays all the user's contacts, each contact should be clickable to start a new conversation&lt;br&gt;
Conversation: Left side pane displayed after user clicks on a conversation summary. Shows entire conversation.&lt;br&gt;
UserProfile: Displays User's username, fullname, lastSeen / online status.&lt;br&gt;
MessageList: All the messages in the conversation.&lt;br&gt;
Message: Each individual message, displayed either on the right or left side of the window depending on whether it was sent or recieved.&lt;br&gt;
AddMessage: Chatbox where the user types the message and clicks send / Enter button to send the message.&lt;/p&gt;

&lt;p&gt;The design of the database collection would closely overlap with some of the components that are displayed on the UI i.e. Conversation, Message, ConversationSummary and an additional collection called Users (to handle authentication/authorization)&lt;/p&gt;

&lt;p&gt;The Node.js backend consisted of APIs handler functions that would be required to perform basic CRUD functionality as well as user sign-up and login.&lt;/p&gt;

&lt;p&gt;Once the development of the UI components, API handlers and the end-to-end integration between Client, Server and Database was complete. The only thing remaining was to implement real-time updates using WebSockets.&lt;/p&gt;

&lt;h2&gt;
  
  
  WebSockets and Azure App Service
&lt;/h2&gt;

&lt;p&gt;Initially I had the WebSocket server code in the same Node.js application as the Webserver (although using different ports) this worked fine on my local environment during development but I soon learned when I tried deploying my app to Azure that I was unable to make calls to my WebSocket server since only &lt;code&gt;port 80 and 443&lt;/code&gt; are exposed by Azure App Service and these were used by the Express webserver. Thus, I ended up having to move all the WebSocket server code into a separate Node.js application so that it could run on the default ports.&lt;/p&gt;

&lt;p&gt;Another key takeaway from this experience was that deploying the WebSocket server app to Azure App Service is a bit of an hassle to say the least.&lt;/p&gt;

&lt;p&gt;For starters, at the time of this writing the Free Tier for Azure App Service on Linux does not support WebSocket connections. The Free Tier for Windows supports only up to 5 concurrent connections following which any client that tries to connect is greeted with a HTTP 503 error. The next App Service plan (Shared Tier) allows up to 35 concurrent connections.&lt;/p&gt;

&lt;p&gt;Furthermore, apps deployed to Azure App service in the Free and Shared tiers have restrictions to the amount of CPU time they are allocated per day (60 and 240 mins respectively). Apps are deallocated from memory if they do not receive incoming requests and are brought back when required which leads to delays (known as cold starts) and an overall terrible user experience.&lt;/p&gt;

&lt;p&gt;Node.js applications that are deployed on Azure App Service also sometimes face issues with WebSocket connections due to the way the handoff occurs between IIS and Node.js via &lt;code&gt;iisnode&lt;/code&gt;. The &lt;code&gt;web.config&lt;/code&gt; file plays an essential role in this and one must ensure that it is present and has the following configuration &lt;code&gt;&amp;lt;webSocket enabled="false" /&amp;gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;I also faced similar issues for another application that I was developing that used Socket.IO instead of raw Websockets and ultimately concluded that it's simply not worth the hassle of using Azure App Service for this use case and found that Heroku was a much simpler and better option.&lt;/p&gt;

&lt;h2&gt;
  
  
  Handling Authentication
&lt;/h2&gt;

&lt;p&gt;I was also handling the user sign-up and authentication logic myself in the server code and storing the credentials in users collection in the database (with hashed passwords). In hindsight I would not recommend this approach since this is not a secure way of going about it. I would absolutely recommend using Firebase for authentication instead due to the relative ease of integration and the improved security that comes with using OAuth / OpenIDConnect based authentication with an identity provider such as Google.&lt;/p&gt;

&lt;h2&gt;
  
  
  Next.js vs create-react-app
&lt;/h2&gt;

&lt;p&gt;Another key lesson learnt was that it would have been much more efficient to have used &lt;code&gt;Next.js&lt;/code&gt; instead of &lt;code&gt;create-react-app&lt;/code&gt; while developing this application since Next.js allows backend code to be written in the application's &lt;code&gt;/pages/api&lt;/code&gt; directory. The pages that are placed in this directory are run as Serverless functions once the Next.js app is deployed on Vercel thereby eliminating the need for a backend server hosted on a separate cloud instance (in this case Azure App Service). Another point to remember is that Serverless functions are essentially stateless by nature therefore if your backend needs to maintain stateful sessions or anything of that nature then going the Serverless route is not recommended.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/aimanjaffer/messaging-app"&gt;All the code for this project can be found here&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>JavaScript Asynchronous Patterns and Closures</title>
      <dc:creator>Aiman Jaffer</dc:creator>
      <pubDate>Wed, 22 Sep 2021 17:28:35 +0000</pubDate>
      <link>https://dev.to/aimanjaffer/javascript-asynchronous-patterns-and-closures-3352</link>
      <guid>https://dev.to/aimanjaffer/javascript-asynchronous-patterns-and-closures-3352</guid>
      <description>&lt;p&gt;It can be daunting to make the transition to frontend web development even for someone who has prior programming experience with strongly-typed or object-oriented languages such as Java. JavaScript has a plethora of quirks that make it a very unique language to say the least, but it is the predominant language of the internet and mastering it is crucial to success as a web developer. These were some of the JavaScript concepts that baffled me when I began (some still do) but I hope this post will help you gain a better understanding of some of these key concepts that you may encounter in the wild.&lt;/p&gt;

&lt;h2&gt;
  
  
  Asynchronous execution of code
&lt;/h2&gt;

&lt;p&gt;JavaScript is a &lt;strong&gt;single-threaded&lt;/strong&gt; language, this means that at any point during a program's execution there can be a maximum of one statement that is being executed which is followed by the next statement and so on. This works fine for statements where the bulk of work to be performed is handled by the CPU (aka &lt;strong&gt;CPU-intensive tasks&lt;/strong&gt;). The problem occurs when a program involves code that performs &lt;strong&gt;I/O-intensive tasks&lt;/strong&gt; (such as network calls, filesystem read/write operations etc.) and is followed by code that performs relatively quicker CPU-bound tasks that don't necessarily rely on the output of these I/O-intensive tasks but are forced to wait for them to finish before they can begin execution (due to the single-threaded nature of JavaScript). For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fs = require('fs');  
const filepath = 'text.txt';
const data = fs.readFileSync(filepath, {encoding: 'utf8'});
let sum  = 3 + 5;
console.log(sum);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example the statements involving calculating and logging the sum of 3 and 5 to the console must wait for the execution of all preceding code even though it is not dependent on the code that precedes it. This is an example of &lt;strong&gt;blocking I/O&lt;/strong&gt;. This situation can be a significant bottleneck in the execution of a program and can lead to a unpleasant experience for the end-user of the program. Fortunately, there are a lot of ways to deal with this situation that are collectively known as asynchronous programming and when dealing with I/O operations specifically this is known as &lt;strong&gt;non-blocking I/O&lt;/strong&gt;.&lt;br&gt;
The 5 concepts we frequently encounter while implementing Asynchronous programming in JavaScript are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Callbacks&lt;/li&gt;
&lt;li&gt;Timeout functions&lt;/li&gt;
&lt;li&gt;Promises&lt;/li&gt;
&lt;li&gt;Async/Await&lt;/li&gt;
&lt;li&gt;Observables (This one is specific to RxJs)&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;
  
  
  Callbacks
&lt;/h3&gt;

&lt;p&gt;To understand callbacks in JavaScript we must first be familiar with the underlying principle that is: &lt;strong&gt;&lt;em&gt;functions are first-class citizens in JavaScript.&lt;/em&gt;&lt;/strong&gt; This means that functions are just like any other JavaScript objects, in that they can be assigned to variables, passed as parameters to other functions and can be returned from other functions (&lt;strong&gt;&lt;em&gt;Higher Order Functions&lt;/em&gt;&lt;/strong&gt;). This feature of JavaScript is crucial in order to implement callbacks as we shall see in the following example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Synchronous Execution example:
function doSomethingWithDataSync (data) {
//...do some I/O intensive task which returns result
return result;
}

let result = doSomethingWithDataSync("Hello");
console.log(result);
let y = 3 + 5;
console.log(y);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The same task can be performed using callbacks asynchronously as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Asynchronous Execution example:
function doSomethingWithDataAsync (data, callback){
//...do some I/O intensive task which returns result
if(error)
callback(error)
else
callback(null, result)
}

doSomethingWithDataAsync("Hello", function(error, data){
if(error)
console.log("Error occured");
else
console.log(data);
});
let y = 3 + 5;
console.log(y);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example we pass a function that takes two arguments &lt;code&gt;error, data&lt;/code&gt; as parameters to the function &lt;code&gt;doSomethingWithDataAsync&lt;/code&gt;. Once the execution of the I/O intensive statement is completed, the callback function is called in one of two ways depending on whether an error occurred or the task executed successfully. In this example execution of statements &lt;code&gt;let y = 3 + 5;&lt;/code&gt; and &lt;code&gt;console.log(y);&lt;/code&gt; are not waiting for the execution of function &lt;code&gt;doSomethingWithDataAsync&lt;/code&gt; and the callback function to complete. We'll now learn about how this callback is moved off the call stack in order to be processed at a later point in time.&lt;/p&gt;

&lt;h3&gt;
  
  
  Timeout functions
&lt;/h3&gt;

&lt;p&gt;Functions such as &lt;code&gt;setTimeout&lt;/code&gt; and &lt;code&gt;setInterval&lt;/code&gt; are perhaps the oldest way of executing code asynchronously in JavaScript. The function &lt;code&gt;setTimeout&lt;/code&gt; takes two parameters: the first is a callback function which contains some code that should be executed and the second is a minimum time (in milliseconds) to wait before the callback function is executed. Note that this is the &lt;strong&gt;minimum time&lt;/strong&gt; and not a guarantee that the callback function will be executed immediately when this timer expires. To understand how this allows JavaScript to execute asynchronous code we must first familiarize ourselves with how the browser executes JavaScript via the Stack, CallbackQueue, Web APIs and the Event Loop.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;setTimeout&lt;/code&gt; and &lt;code&gt;setInterval&lt;/code&gt; belong to a category of functions that are collectively known as &lt;strong&gt;Web APIs&lt;/strong&gt;. These functions are not part of the JavaScript language themselves but are APIs exposed by the browser in order to aid developers.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Call Stack&lt;/strong&gt; (or simple the Stack) is a LIFO (last-in first-out) data structure used by browers to determine the execution context of a particular piece of code. Whenever a function is called it is add to the top of the stack and when the function completes it is removed from the stack. Thus the function at the top of the stack is always the currently executing function.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Event Queue&lt;/strong&gt; is a data structure used by the browser to store functions that are waiting to be executed once the stack is empty.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Event Loop&lt;/strong&gt; is the browser construct that checks whether the stack is empty and moves the function in the front of the Queue to the Call Stack.&lt;/p&gt;

&lt;p&gt;Now that we know what each of these individual pieces are, let's see how they work together in the following example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log("Before setTimeout callback function");
setTimeout(()=&amp;gt;{
console.log("Inside setTimeout callback function");
},1000);
console.log("After setTimeout callback function");

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

&lt;/div&gt;



&lt;p&gt;The output of this code snippet should be as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Before setTimeout callback function
After setTimeout callback function
Inside setTimeout callback function
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With a gap of at least one second between when the second and third statements are displayed.&lt;/p&gt;

&lt;p&gt;Let's take a look at the individual steps that allow this behavior to occur:&lt;br&gt;
(We assume that before we begin both the Call Stack and Event Queue are empty)&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;console.log("Before...")&lt;/code&gt; is the first statement that should be executed hence it is added to the stack. The message is displayed on the console and then the function is removed from the stack.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;setTimeout&lt;/code&gt; is called with a callback function and a minimum wait time of 1 second. &lt;/li&gt;
&lt;li&gt;setTimeout is added to the top of the stack and since it is a Web API it is immediately removed from the top of the stack.&lt;/li&gt;
&lt;li&gt;The browser registers the timer and the associated callback function and begins the timer.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;console.log("After...")&lt;/code&gt; is the next statement that should be executed hence it is added to the stack. The message is displayed on the console and then the function is removed from the stack.&lt;/li&gt;
&lt;li&gt;Once the timer expires after the specified duration of time, the callback function is added to the &lt;strong&gt;Event Queue&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;Event Loop&lt;/strong&gt; then checks whether the stack is empty and then moves the callback function (which is currently at the front of the Event Queue) to the stack for execution.&lt;/li&gt;
&lt;li&gt;The callback function executes, the message is logged to the console.
8.The callback function is removed from the stack.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;
  
  
  Promises
&lt;/h3&gt;

&lt;p&gt;One of the issues observed while programming utilizing callbacks is that &lt;strong&gt;code readability&lt;/strong&gt; suffers, especially when dealing with nested callback functions. Promises offer an alternate syntax that significantly improves code readability through the use of &lt;strong&gt;operation chaining&lt;/strong&gt; (as opposed to nesting). A Promise represents the eventual result of an asynchronous operation and it's associated value. At any given time, a promise can be in one of 3 states:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Pending&lt;/li&gt;
&lt;li&gt;Fulfilled&lt;/li&gt;
&lt;li&gt;Rejected&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We can deal with a promise that is in the fullfilled state via the &lt;code&gt;.then(onFulfillment)&lt;/code&gt; method and perform error handling on a promise that is rejected via the &lt;code&gt;.catch(onRejection)&lt;/code&gt; method. While chaining multiple promises all errors can be handled by a single &lt;code&gt;.catch()&lt;/code&gt; placed at the end of the chain. An alternative to this is to specify both the &lt;code&gt;onFulfillment&lt;/code&gt; and &lt;code&gt;onRejection&lt;/code&gt; callbacks as arguments to &lt;code&gt;.then()&lt;/code&gt; as &lt;code&gt;.then(onFulfillment, onRejection)&lt;/code&gt;. Internally a promise is fulfilled via the static method &lt;code&gt;Promise.resolve(valueForSuccess)&lt;/code&gt; and rejected via the static method &lt;code&gt;Promise.reject(valueForFailure)&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;
  
  
  Async/Await
&lt;/h3&gt;

&lt;p&gt;Async/Await allows developers to write asynchronous code that very in style closely resembles synchronous code thus &lt;strong&gt;enhancing code readability&lt;/strong&gt; even further than promise-style asynchronous code. Functions that contain asynchronous operations are marked with the &lt;code&gt;async&lt;/code&gt; keyword and individual operations that are performed asynchronously are marked with the &lt;code&gt;await&lt;/code&gt; keyword. Use of &lt;code&gt;async await&lt;/code&gt; allows developers to use regular &lt;code&gt;try catch&lt;/code&gt; blocks to perform error handling rather than &lt;code&gt;.then()&lt;/code&gt; and &lt;code&gt;.catch()&lt;/code&gt;. Also, Async functions are &lt;strong&gt;guaranteed to return Promises&lt;/strong&gt; even if they are not explicitly created.&lt;/p&gt;
&lt;h3&gt;
  
  
  Observables
&lt;/h3&gt;

&lt;p&gt;Observables are a technique for handling the execution of asynchronous tasks in the &lt;strong&gt;Angular&lt;/strong&gt; framework through the use of &lt;strong&gt;RxJs&lt;/strong&gt; library. Observables &lt;strong&gt;support multiple values&lt;/strong&gt; as opposed to Promises that resolve to a single value. This pattern involves two actors. A Publisher that creates an Observable and provides a subscriber function. Any number of Consumers that call the &lt;code&gt;.subscribe()&lt;/code&gt; method on the observable. The Consumer then receives new data via the Observable until the function completes execution or until they unsubscribe. The &lt;code&gt;.subscribe()&lt;/code&gt; method takes three functions as parameters: &lt;code&gt;next, error, complete&lt;/code&gt;. The first parameter is mandatory whereas the other two are optional. The &lt;code&gt;next&lt;/code&gt; function is executed when the publisher publishes a new value, the &lt;code&gt;error&lt;/code&gt; function is executed when the publisher sends an error notification and the &lt;code&gt;complete&lt;/code&gt; function is executed when execution of the observable's subscriber function is complete.&lt;/p&gt;
&lt;h2&gt;
  
  
  Closures &amp;amp; Functions as First class Citizens
&lt;/h2&gt;

&lt;p&gt;A closure in JavaScript is simply the combination of a function and the variables that it has access to when it was created. Let's understand this with and example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function outerFunc(){
var playerName = "Michael Jordan";
function innerFunction(){
console.log("Player is: ", playerName);
} 
innerFunction();
}
outerFunc();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output of this code is &lt;code&gt;Player is: Michael Jordan&lt;/code&gt;, pretty straightforward so far right? Now let's see what happens when we return the &lt;code&gt;innerFunction&lt;/code&gt; from the &lt;code&gt;outerFunction&lt;/code&gt; instead of calling it directly (We are allowed to do this because in JavaScript functions are objects). For Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function outerFunc(){
var playerName = "Michael Jordan";
function innerFunction(){
console.log("Player is: ", playerName);
} 
return innerFunction;
}
var getPlayerName = outerFunc();
getPlayerName();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What do you expect will happen?&lt;/p&gt;

&lt;p&gt;You might be inclined to think that since the inner function is now being called from a different context than that in which it was initially created inside it would not have access to the &lt;code&gt;playerName&lt;/code&gt; variable. Go ahead try executing this code and see what happens for yourself.&lt;/p&gt;

&lt;p&gt;You may be surprised to find that the output remains unchanged from the previous example. This is because functions in JavaScript are &lt;strong&gt;Closures&lt;/strong&gt;, this means that functions once created always have access to the variables in the lexical scope in which they were defined.&lt;/p&gt;

&lt;p&gt;Hope this was helpful !! &lt;br&gt;
Links to useful resources below:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise"&gt;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing"&gt;https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await"&gt;https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://angular.io/guide/observables"&gt;https://angular.io/guide/observables&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://angular.io/guide/comparing-observables"&gt;https://angular.io/guide/comparing-observables&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;
&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/8aGhZQkoFbQ"&gt;
&lt;/iframe&gt;
&lt;/li&gt;
&lt;/ol&gt;

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