<?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: Vasil Vasilev</title>
    <description>The latest articles on DEV Community by Vasil Vasilev (@vasilgvasilev).</description>
    <link>https://dev.to/vasilgvasilev</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%2F1116918%2F7ed668d1-ae6f-47fe-b0aa-8ed6a729c008.jpeg</url>
      <title>DEV Community: Vasil Vasilev</title>
      <link>https://dev.to/vasilgvasilev</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/vasilgvasilev"/>
    <language>en</language>
    <item>
      <title>How the `.then()` method interacts with the JavaScript event loop.</title>
      <dc:creator>Vasil Vasilev</dc:creator>
      <pubDate>Sat, 30 Mar 2024 16:28:35 +0000</pubDate>
      <link>https://dev.to/vasilgvasilev/how-the-then-method-interacts-with-the-javascript-event-loop-146g</link>
      <guid>https://dev.to/vasilgvasilev/how-the-then-method-interacts-with-the-javascript-event-loop-146g</guid>
      <description>&lt;h2&gt;
  
  
  Async via Web APIs
&lt;/h2&gt;

&lt;p&gt;Why do we need them? So that we can have non-blocking operations. We have our code and javascript executes synchronously so what if we need to fetch some data on a remote server. Execution stops until the data is fetched. That is hardly efficient. We rely on the Javascript environment that gives us Web APIs to make async non-blocking operations possible. One popular option to do this fetching of data and no block the main thread is via Fetch API. But what actually happens underneath.&lt;/p&gt;

&lt;h2&gt;
  
  
  Promises
&lt;/h2&gt;

&lt;p&gt;To understand what happens underneath, I will use a more simple API -&amp;gt; setTimeout in conjunction with Promise, since the same process is relevant for any other Web API. We rely on setTimeout to extract the callback we pass into it from the call stack (main thread) so as to not block it until some moment in the future (with setTimeout we know the minimum amount of time this moment will expire in).&lt;/p&gt;

&lt;p&gt;Consider the following example for any future reference:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;new Promise((resolve) =&amp;gt; {
    setTimeout(()=&amp;gt;resolve('Done!'), 100);
})
    .then(result =&amp;gt; console.log(result))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The function we pass into the setTimeout is actually the resolve of a Promise. So, in effect, we want the promise to be resolved after the setTimeout is executed (meaning being extracted from the main thread, set as a macroTask, await the clearing up of the main thread and finally re-introduced and executed in the main thread). To truly understand Promises, you have to understand the connection between resolve and .then().&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frtip2soujuq9k2htli2j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frtip2soujuq9k2htli2j.png" alt="Image description" width="571" height="712"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  [[PromiseFulfillReactions]]
&lt;/h2&gt;

&lt;p&gt;Promises in JavaScript represent an eventual completion (or failure) of an asynchronous operation and its resulting value. The &lt;code&gt;[[PromiseFulfillReactions]]&lt;/code&gt; and &lt;code&gt;[[PromiseRejectReactions]]&lt;/code&gt; are internal properties of a Promise that hold the functions (handlers) to be executed when the Promise is fulfilled or rejected.&lt;/p&gt;

&lt;p&gt;The [[PromiseFulfillReactions]] has among others a PromiseReaction field with [[Handelers]], meaning what we put in the .then(). This field gets triggered when the promise is fulfilled. When does the promise get fulfilled -&amp;gt; when the acync operation that was in the task Queue gets pack in the call stack and is executed.&lt;/p&gt;

&lt;p&gt;So basically, we have an async operation (setTimeout), that async operation has the resolve of the Promise. When the async operation gets back into the call stack and gets executed, the resolve of the promise gets executed.&lt;br&gt;
Namely, the Promise becomes fulfilled and it triggers the PromiseFullfillReaction Handler (which is the code inside .then()). result =&amp;gt; console.log(result) is set onto the microTask Queue until the call stack is free and when it is free, it finally gets the actual parameter 'Done!' applied to be executed. &lt;/p&gt;

</description>
      <category>promises</category>
      <category>javascript</category>
      <category>then</category>
      <category>resolve</category>
    </item>
    <item>
      <title>Why we need event capture and event bubbling?</title>
      <dc:creator>Vasil Vasilev</dc:creator>
      <pubDate>Sat, 09 Sep 2023 11:52:22 +0000</pubDate>
      <link>https://dev.to/vasilgvasilev/why-we-need-event-capture-and-event-bubbling-1632</link>
      <guid>https://dev.to/vasilgvasilev/why-we-need-event-capture-and-event-bubbling-1632</guid>
      <description>&lt;p&gt;Since events are a fundamental part of any web application, we need a way to manage those events and interconnect them to form a whole web page. The structure of any web page is represented by the DOM tree, so this is also the chain that serves as a link between nodes/elements which can fire events. Looking at the DOM tree and knowing that Javascript initial purpose was to be scripting language for static web sites, we can infer why is Javascript's inheritance based on the prototype model. It two interconnects via a chain of objects that each have a prototype which in turn is also an object. A DOM tree is similar with its elements that consists of properties and methods, but also of links to parent and children elements. &lt;/p&gt;

&lt;p&gt;But to go back to the subject matter of the current article, the two event propagation models through which we manage and control the flow of events in the Document Object Model (DOM) are event bubbling and event capture. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--BNfbwgwW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ybj1kpknix30dxknb9gn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--BNfbwgwW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ybj1kpknix30dxknb9gn.png" alt="Image description" width="640" height="480"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;So, what happens when we click on a button on a web page?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Capture&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Well, we would have to first open the root element -&amp;gt; window object, then document, then html then down the tree to the event that actually triggered the event. This is also called the capture phase, we capture the event triggering element.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bubbling&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The reverse flow is named the bubbling phase. From the event.target to the outermost layer of the DOM tree. &lt;/p&gt;

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

&lt;p&gt;&lt;strong&gt;But why do we need them both? Is it not enough to 'capture' the element that triggered the event and save resources on bubbling?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The reason for needing both capture and bubbling is that in reality, we rarely have one element with one event handler. &lt;/p&gt;

&lt;p&gt;So, what if we click on a button that is within a div and both of them have an event hanlder? The capture phase will go top-down and trigger the event handler of both the target element - the button and its parent element - the div. We do not want that. &lt;strong&gt;We want isolation of event handling.&lt;/strong&gt; Thus, we need the capture phase to reach the target element, but also a bubbling phase from that very target element up to the top, to have control over the event propagation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;e.stopPropagation()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To do this, we apply the e.stopPropagation() method at the top of our event handling function (event obviously passed in as a prop), so that we stop the propagation from going up the parent elements of the target element.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;const Example &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    handleCallFarm&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        console.log&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Hello, whole farm"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    handleChicken&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        console.log&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Hello, chicken!"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    handleCows&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        console.log&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Hello, cows!"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    handlePigs&lt;span class="o"&gt;(&lt;/span&gt;event&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        event.stopPropagation&lt;span class="o"&gt;()&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; // USED HERE!
        console.log&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Hello, pigs!"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    render&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;
            &amp;lt;div &lt;span class="nv"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"parent-element"&lt;/span&gt; &lt;span class="nv"&gt;onClick&lt;/span&gt;&lt;span class="o"&gt;={&lt;/span&gt;handleCallFamily&lt;span class="o"&gt;}&amp;gt;&lt;/span&gt; 
                &amp;lt;button &lt;span class="nv"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"child-element"&lt;/span&gt; &lt;span class="nv"&gt;onClick&lt;/span&gt;&lt;span class="o"&gt;={&lt;/span&gt;handleChicken&lt;span class="o"&gt;}&amp;gt;&lt;/span&gt;Call Chicken&amp;lt;/button&amp;gt;
                &amp;lt;button &lt;span class="nv"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"child-element"&lt;/span&gt; &lt;span class="nv"&gt;onClick&lt;/span&gt;&lt;span class="o"&gt;={&lt;/span&gt;handleCows&lt;span class="o"&gt;}&amp;gt;&lt;/span&gt;Call Cows&amp;lt;/button&amp;gt;
                &amp;lt;button &lt;span class="nv"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"child-element"&lt;/span&gt; &lt;span class="nv"&gt;onClick&lt;/span&gt;&lt;span class="o"&gt;={&lt;/span&gt;handlePigs&lt;span class="o"&gt;}&amp;gt;&lt;/span&gt;Call Pigs&amp;lt;/button&amp;gt;
            &amp;lt;/div&amp;gt;
        &lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;So if we click: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Call Chicken -&amp;gt; we will print:
"Hello, chicken!"
"Hello, whole farm"&lt;/li&gt;
&lt;li&gt;Call Cows -&amp;gt; we will print:
"Hello, cows!"
"Hello, whole farm"&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;BUT if we click: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Call Pigs -&amp;gt; we will print only:
"Hello, pigs!"&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That is because we stopped the propagation from going up the parent element. Thus, the most popular use case of the bubbling phase -&amp;gt; event delegation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Event Delegation&lt;/strong&gt;&lt;br&gt;
Bubbling is essential for event delegation, which is a powerful technique to optimize event handling. By attaching a single event listener to a common ancestor of multiple elements, you can efficiently handle events for all those elements without adding individual event listeners to each one. &lt;/p&gt;

&lt;p&gt;As we have come to understand now that would not be possible with capture alone, because we will always have both the parent and the child event handler firing. However, with bubbling, we start from the child and have the capability of stopping further propagation, which enables us to reduce the amount of event handlers by having only one on the parent element. Thus, we both have less event handlers, but also we do not loose our control to precisely target the child element.&lt;/p&gt;

&lt;p&gt;Simply said, we have a child element that triggers an event without the need for handler. Its parent, tho, has a handler, and since bubbling goes up the DOM tree, we intercept the event coming from the child at the parent level.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;An important additional take from this article is the difference between event.target and event.currentTarget. They help illustrate the significance of element that cause the event and element that has an event listener attached to it.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Event.target vs Event.currentTarget&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;event.target is the most deeply nested element that caused the event.&lt;/li&gt;
&lt;li&gt;event.currentTarget is the element that listens to the event (where the event listener is attached to).
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;const Example &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    handleCallFarm&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        console.log&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Hello, whole farm"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    handleChicken&lt;span class="o"&gt;(&lt;/span&gt;event&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        console.log&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Hello, chicken!"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        console.log&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"event.target:"&lt;/span&gt;, event.target&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        console.log&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"event.currentTarget"&lt;/span&gt;, event.currentTarget&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    handleCows&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        console.log&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Hello, cows!"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    handlePigs&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        event.stopPropagation&lt;span class="o"&gt;()&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; // USED HERE!
        console.log&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Hello, pigs!"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    render&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;
            &amp;lt;div &lt;span class="nv"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"parent-element"&lt;/span&gt; &lt;span class="nv"&gt;onClick&lt;/span&gt;&lt;span class="o"&gt;={&lt;/span&gt;handleCallFamily&lt;span class="o"&gt;}&amp;gt;&lt;/span&gt; 
                &amp;lt;button &lt;span class="nv"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"child-element"&lt;/span&gt; &lt;span class="nv"&gt;onClick&lt;/span&gt;&lt;span class="o"&gt;={&lt;/span&gt;handleChicken&lt;span class="o"&gt;}&amp;gt;&lt;/span&gt;Call Chicken&amp;lt;/button&amp;gt;
                &amp;lt;button &lt;span class="nv"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"child-element"&lt;/span&gt; &lt;span class="nv"&gt;onClick&lt;/span&gt;&lt;span class="o"&gt;={&lt;/span&gt;handleCows&lt;span class="o"&gt;}&amp;gt;&lt;/span&gt;Call Cows&amp;lt;/button&amp;gt;
                &amp;lt;button &lt;span class="nv"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"child-element"&lt;/span&gt; &lt;span class="nv"&gt;onClick&lt;/span&gt;&lt;span class="o"&gt;={&lt;/span&gt;handlePigs&lt;span class="o"&gt;}&amp;gt;&lt;/span&gt;Call Pigs&amp;lt;/button&amp;gt;
            &amp;lt;/div&amp;gt;
        &lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;So if we click: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Call Chicken -&amp;gt; we will print:
"Hello, chicken!"
"event.target:", Call Chicken
"event.currentTarget", Call Chicken&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;BUT if we click: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Call Chicken, yet this time target and current target are attached to the parent element:
"Hello, whole farm!"
"event.target:", Call Chicken
"event.currentTarget", 
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;const Example &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    handleCallFarm&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        console.log&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Hello, whole farm"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        console.log&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"event.target:"&lt;/span&gt;, event.target&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        console.log&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"event.currentTarget"&lt;/span&gt;, event.currentTarget&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    handleChicken&lt;span class="o"&gt;(&lt;/span&gt;event&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        console.log&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Hello, chicken!"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

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

    handleCows&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        console.log&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Hello, cows!"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    handlePigs&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        event.stopPropagation&lt;span class="o"&gt;()&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; // USED HERE!
        console.log&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Hello, pigs!"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    render&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;
            &amp;lt;div &lt;span class="nv"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"parent-element"&lt;/span&gt; &lt;span class="nv"&gt;onClick&lt;/span&gt;&lt;span class="o"&gt;={&lt;/span&gt;handleCallFamily&lt;span class="o"&gt;}&amp;gt;&lt;/span&gt; 
                &amp;lt;button &lt;span class="nv"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"child-element"&lt;/span&gt; &lt;span class="nv"&gt;onClick&lt;/span&gt;&lt;span class="o"&gt;={&lt;/span&gt;handleChicken&lt;span class="o"&gt;}&amp;gt;&lt;/span&gt;Call Chicken&amp;lt;/button&amp;gt;
                &amp;lt;button &lt;span class="nv"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"child-element"&lt;/span&gt; &lt;span class="nv"&gt;onClick&lt;/span&gt;&lt;span class="o"&gt;={&lt;/span&gt;handleCows&lt;span class="o"&gt;}&amp;gt;&lt;/span&gt;Call Cows&amp;lt;/button&amp;gt;
                &amp;lt;button &lt;span class="nv"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"child-element"&lt;/span&gt; &lt;span class="nv"&gt;onClick&lt;/span&gt;&lt;span class="o"&gt;={&lt;/span&gt;handlePigs&lt;span class="o"&gt;}&amp;gt;&lt;/span&gt;Call Pigs&amp;lt;/button&amp;gt;
            &amp;lt;/div&amp;gt;
        &lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

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

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Javascript is single or multi-threaded?</title>
      <dc:creator>Vasil Vasilev</dc:creator>
      <pubDate>Thu, 07 Sep 2023 14:33:40 +0000</pubDate>
      <link>https://dev.to/vasilgvasilev/javascript-is-single-or-multi-threaded-486e</link>
      <guid>https://dev.to/vasilgvasilev/javascript-is-single-or-multi-threaded-486e</guid>
      <description>&lt;p&gt;Javascript is a synchronous programming language. But it is also the language of the Web which requires asynchronous fetching of data, also we want user interactivity, namely, functions that are event driven and executed based on user behavior only. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Callbacks and Promises&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We achieve this by creating pieces of code that do not execute immediately when the program initializes. Those pieces of code are also known as callbacks and promises. Initially, the most basic approach was with pure callbacks, but the very nature of function definitions lead to the so called 'callback hell' of nested callbacks. Thus, a more refined tool emerged - a promise. Nowadays, we also have the async/await as a popular alternative to the '.then()' resolving of promises. However this article's purpose is not to educate on the basics of dealing with asynchronous requests. &lt;br&gt;
It attempts to delve into the nature of Javascript and explain how come asynchronous tools such as callbacks and promises are part of it.&lt;/p&gt;

&lt;p&gt;So how come a single-threaded programming language have asynchronous tools at its disposal?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Javascript runtime&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The straightforward answer is - Javascript runtime. Nowadays, Javascript is not only a scripting language with the simple purpose of toggling a button on a static web page, it a fully capable programming language. Thus, to understand how a single-threaded language can achieve concurrency, let's start with the following image.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--W6S_Zk-1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fhvykdksmn3jt72q390n.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--W6S_Zk-1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fhvykdksmn3jt72q390n.jpg" alt="Image description" width="700" height="561"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We see a JS engine and a few additional features - Web API, Event loop and a Queue. When we say single thread, we refer to the JS engine. Simply said, this relates to the code you have written and its execution contexts, while the additional features 'create' an additional thread. So, the runtime consists of two parts - your code and some other external code both producing the whole application. So, modern Javascript always needs a runtime environment to execute and the most popular one is the browser. Another popular one is Node.js. &lt;/p&gt;

&lt;p&gt;But now, let's look at the mechanism of a callback function, applying what we have learned about runtime environment already.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Callbacks&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="k"&gt;function &lt;/span&gt;fetchData&lt;span class="o"&gt;(&lt;/span&gt;callback&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
  setTimeout&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    const data &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'Async data'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    callback&lt;span class="o"&gt;(&lt;/span&gt;data&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; // Execute the callback &lt;span class="k"&gt;function &lt;/span&gt;with the data
  &lt;span class="o"&gt;}&lt;/span&gt;, 1000&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;function &lt;/span&gt;processData&lt;span class="o"&gt;(&lt;/span&gt;data&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
  console.log&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'Received data: '&lt;/span&gt;, data&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

fetchData&lt;span class="o"&gt;(&lt;/span&gt;processData&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; // Pass the processData &lt;span class="k"&gt;function &lt;/span&gt;as a callback
console.log&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'Fetching data...'&lt;/span&gt;&lt;span class="o"&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 Line of Execution:&lt;/p&gt;

&lt;p&gt;console.log('Fetching data...'); // This line is executed first.&lt;br&gt;
console.log('Received data: Async data'); // This line is executed second.&lt;/p&gt;

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

&lt;ol&gt;
&lt;li&gt;fetchData(processData) is triggered first&lt;/li&gt;
&lt;li&gt;setTimeout is called with a delay of 1000 milliseconds.&lt;/li&gt;
&lt;li&gt;While waiting for the timeout, the program continues by executing console.log('Fetching data...');&lt;/li&gt;
&lt;li&gt;After 1000 milliseconds (1 second), the callback function processData is executed with the data 'Async data'.&lt;/li&gt;
&lt;li&gt;Inside processData, the statement console.log('Received data:', data); is finally executed.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So, the final order of printing statements is:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;"Fetching data..."&lt;/li&gt;
&lt;li&gt;"Received data: Async data"&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Thus, the "Fetching data..." console.log executes before the fetchData function.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How is this possible?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;How does Javascript, which is single-threaded, 'know' to continue interpreting the code and execute the subsequent console.log("Fetching data..."), even though it has another task seemingly on standby (fetchData function).&lt;/p&gt;

&lt;p&gt;As I said, when we say single-threaded, we refer to the execution mechanism of the JS engine. The Javascript engine is responsible for the execution contexts, namely, managing the  memory heap and the call stack. The memory heap stores all the variables defined in our JS code while the call stack performs the operations (function execution). &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--mV4JNFVi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6gw1zhcbl86pnf7pwk2i.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--mV4JNFVi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6gw1zhcbl86pnf7pwk2i.gif" alt="Image description" width="600" height="337"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So, back to the current problem, single-threaded means only one call stack. One call stack, in turn, means only one piece of code can be executed at a time. &lt;/p&gt;

&lt;p&gt;In our case with console.log('Fetching data...') and fetchData function, given the nature of Javascript to be non-blocking, Javascript does not wait for the response of the callback, but moves on with the interpretation of the subsequent blocks of code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why does it not wait?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The answer - the callback fetchData function is 'extracted' from the call stack of the current main thread and logically the execution continues with console.log('Fetching data...').&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;But where is this callback 'extracted' to?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The general answer not only for callbacks is that any such asynchronous function utilizes the Web API by relying on the Event loop to manage its queue priority when to re-enter the main thread call stack.&lt;/p&gt;

&lt;p&gt;In the case of callbacks, the Timer Web API executes the setTimeout and the Event loop puts the result of that function in the Tasks Queue. That is also why the delay set in setTimeout is known as a minimum delay time. It is unclear when exactly the call stack will be freed up so that a new event cycle can be executed and tasks from the queue be added to it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--WPNRbcXX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iqqw1url4bhn1kw1j9gu.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--WPNRbcXX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iqqw1url4bhn1kw1j9gu.jpg" alt="Image description" width="800" height="336"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Let's now look at how promises are resolved in the Javascript runtime.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Promises&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;const promise &lt;span class="o"&gt;=&lt;/span&gt; new Promise&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;resolve&lt;/span&gt;&lt;span class="o"&gt;=&amp;gt;{&lt;/span&gt;
  resolve&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Promise"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;, reject &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

&lt;span class="o"&gt;})&lt;/span&gt;

promise.then&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;res&lt;/span&gt;&lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;console.log&lt;span class="o"&gt;(&lt;/span&gt;res&lt;span class="o"&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the case of promises, the promise is set into the Microtask Queue which the event loop ranks with higher priority than regular tasks such as setTimeout callbacks. Meaning when/if a promise is fulfilled, its result is added to the microtask queue, ensuring that it will be executed before the next (regular) task in the event loop.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--tG6ljtIp--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eor8xa4ok4c83t6gx2w1.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--tG6ljtIp--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eor8xa4ok4c83t6gx2w1.gif" alt="Image description" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Inversion of control&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Thus, with simple words, the Javascript runtime adds threads and concurrency to the otherwise, single threaded programming language.&lt;/p&gt;

&lt;p&gt;That would also be known as inversion of control, a very popular term in programming. The code result becomes dependant on an external factor, namely, the additional features that come with every Javascript runtime. Control of execution is inverted and handed over to an external entity as described above. In &lt;/p&gt;

</description>
    </item>
    <item>
      <title>The Importance Of Immutability In React</title>
      <dc:creator>Vasil Vasilev</dc:creator>
      <pubDate>Thu, 24 Aug 2023 11:25:51 +0000</pubDate>
      <link>https://dev.to/vasilgvasilev/the-importance-of-immutability-in-react-1o71</link>
      <guid>https://dev.to/vasilgvasilev/the-importance-of-immutability-in-react-1o71</guid>
      <description>&lt;p&gt;Immutability is a crucial concept in React. It refers to the practice of not changing the original data structures once they are created. Instead, when modifications are required, new data structures are created to represent the updated state. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why is immutability manually applied?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In JavaScript, objects and arrays are reference types. When you mutate an object, its reference remains the same, even if the content changes. This can lead to unexpected behavior when comparing objects for equality or when checking for changes. Immutable data ensures that changes result in new references, facilitating accurate comparison checks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why is immutability encouraged in React specifically?&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Predictable Data Flow&lt;/strong&gt;: In React, components re-render when their state or props change. If the data within a component's state is immutable, it becomes easier to predict when a re-render will occur. This predictability is essential for maintaining a stable and efficient application performance.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;It improves performance&lt;/strong&gt;: React uses a virtual DOM to render components. The virtual DOM is a lightweight representation of the actual DOM. When an object is immutable, React can simply compare the old and new objects to see if anything has changed. If nothing has changed, React can skip the rendering step, which can improve performance.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Debugging&lt;/strong&gt;: It can help to prevent bugs. When objects are immutable, it is more difficult to accidentally modify the state of an object in a way that can cause a bug.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;How to achieve immutability in React?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;One way is to use the &lt;strong&gt;&lt;em&gt;const&lt;/em&gt;&lt;/strong&gt; keyword to declare variables. Variables declared with the const keyword cannot be changed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// bad: Because a new object is created every time React renders.

function App() {
  const [visible, stop] = useElementVisibility(ref, {
    root: null,
    rootMargin: "0px",
    threshold: 1,
  });
}

const options = {
  root: null,
  rootMargin: "0px",
  threshold: 1,
};

// good: Because the reference to the object remains unchanged.

function App() {
  const [visible, stop] = useState(ref, options);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Alternatively, you can choose to use the &lt;em&gt;useMemo&lt;/em&gt; function to wrap it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// good: Because the reference to the object remains unchanged.

function App() {
  const options = useMemo(() =&amp;gt; {
    return {
      root: null,
      rootMargin: "0px",
      threshold: 1,
    };
  }, []);

  const [visible, stop] = useState(ref, options);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Understanding the useCallback hook</title>
      <dc:creator>Vasil Vasilev</dc:creator>
      <pubDate>Wed, 09 Aug 2023 12:45:03 +0000</pubDate>
      <link>https://dev.to/vasilgvasilev/understanding-the-usecallback-hook-4d5b</link>
      <guid>https://dev.to/vasilgvasilev/understanding-the-usecallback-hook-4d5b</guid>
      <description>&lt;p&gt;&lt;strong&gt;Official Definition&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;According to the React official documentation as of the time of writing this article, useCallback is a React Hook that lets you cache a function definition between re-renders.&lt;br&gt;
Thus, we try to achieve efficiency by avoiding re-rendering of unnecessary code that can be memoized.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How does it work?&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const cachedFn = useCallback(fn, dependencies)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The useCallback hook takes two arguments: the function to memoize, and an array of dependencies. The dependencies are the values that the function depends on. If any of the dependencies change, the function will be re-run. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why don't we just store the function outside the component?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We may be tempted to store the function as any other value stored in a variable (in JS, functions are first class functions).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from 'react';

// Outside the component
function myFunction() {
  console.log('Function executed');
  return 'Function result';
}

function ParentComponent() {
  const [count, setCount] = useState(0);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; setCount(count + 1)}&amp;gt;Increment&amp;lt;/button&amp;gt;
      &amp;lt;ChildComponent func={myFunction} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

function ChildComponent({ func }) {
  const result = func();

  return &amp;lt;div&amp;gt;{result}&amp;lt;/div&amp;gt;;
}

export default ParentComponent;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, even if you click the "Increment" button and cause the ParentComponent to re-render, the myFunction outside the component won't re-run unless explicitly called. However, if myFunction was used in the rendering logic of the ChildComponent, the child component might re-render if the parent component's re-render caused changes in the prop values.&lt;/p&gt;

&lt;p&gt;So, every time the component re-renders, myFunction will be re-run, even if there is no conditional but simply some plain console logging and returning of a string. This can be inefficient, because myFunction may be expensive to run.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The useCallback hook goes a step further in limiting re-renders&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The hook limits re-renders to only when one of the dependencies' value change:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState, useCallback } from 'react';

// Inside component as a definiton, but actually inside React cache

function ParentComponent() {
  const [count, setCount] = useState(0);
  const myFunc = useCallback(()=&amp;gt;{
     function myFunction() {
        console.log('Function executed');
        return 'Function result';
     }
  },[])

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; setCount(count + 1)}&amp;gt;Increment&amp;lt;/button&amp;gt;
      &amp;lt;ChildComponent func={myFunc} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

function ChildComponent({ func }) {
  const result = func();

  return &amp;lt;div&amp;gt;{result}&amp;lt;/div&amp;gt;;
}

export default ParentComponent;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the myFunction function will not be re-rendered even if the update of the ParentComponent's state triggers a re-render in the ChildComponent state via the props.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;But where is the function stored?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When using the useCallback hook in React, the function is stored outside of the render cycle. The purpose of useCallback is to return a memoized version of the function, meaning that it retains the &lt;strong&gt;same memory reference across renders&lt;/strong&gt; unless one of the variables in its dependency array changes. &lt;/p&gt;

&lt;p&gt;So to understand the useCallback hook, you have to understand how exactly it limits re-renders. Thus, one must &lt;strong&gt;look into the dependency array&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;With simple words, the dependency array plays the vital role to control &lt;em&gt;when it is acceptable to allow re-renders&lt;/em&gt;. That would be if a variable that the function depends on, changes its value. &lt;/p&gt;

&lt;p&gt;A more complex example would be an onCancel function. This function is part of a personal project of mine - &lt;a href="https://github.com/VasilGVasilev/airbnb/blob/main/airbnb/app/properties/PropertiesClient.tsx"&gt;Airbnb clone&lt;/a&gt;. It accepts an id of an item and updates the Front-End via update of state and the Back-End via an axios request.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;const onCancel &lt;span class="o"&gt;=&lt;/span&gt; useCallback&lt;span class="o"&gt;((&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;: string&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    // del FE
    setDeletingId&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    // del BE
    axios.delete&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="sb"&gt;`&lt;/span&gt;/api/reservations/&lt;span class="k"&gt;${&lt;/span&gt;&lt;span class="nv"&gt;id&lt;/span&gt;&lt;span class="k"&gt;}&lt;/span&gt;&lt;span class="sb"&gt;`&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
        .then&lt;span class="o"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            toast.success&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'Reservation cancelled'&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            router.refresh&lt;span class="o"&gt;()&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;})&lt;/span&gt;
        .catch&lt;span class="o"&gt;((&lt;/span&gt;error&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            toast.error&lt;span class="o"&gt;(&lt;/span&gt;error?.response?.data?.error&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;})&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;, &lt;span class="o"&gt;[&lt;/span&gt;router]&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;So why do we put the &lt;em&gt;router&lt;/em&gt; variable in the dependency array?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The &lt;em&gt;router&lt;/em&gt; variable may change between the time we trigger the cancel function and the time the router.refresh() method is called. To ensure that the onCancel function is re-evaluated, we need to add the router variable to the dependency array of the useCallback hook.&lt;/p&gt;

&lt;p&gt;The opposite is true for the setDeletingId. It does change a state if you look into the whole code, but this state does not change in any way the variables that the onCancel function depends on.&lt;/p&gt;

&lt;p&gt;Therefore, the dependency array is a crucial instrument that must be configured so that the useCallback hook always works with up-to-date variables it may depend on. In a sense, it serves the opposite purpose of useCallback, since it allows for re-renders to happen, so that useCallback can have the most recent data it works with. But it also limits the re-renders up to the sanitary minimum to avoid any waste of resources that complex functions inside component may cause.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Copying an Array in Javascript</title>
      <dc:creator>Vasil Vasilev</dc:creator>
      <pubDate>Fri, 28 Jul 2023 16:34:19 +0000</pubDate>
      <link>https://dev.to/vasilgvasilev/copying-an-array-in-javascript-2dg3</link>
      <guid>https://dev.to/vasilgvasilev/copying-an-array-in-javascript-2dg3</guid>
      <description>&lt;p&gt;&lt;strong&gt;Refer to this visualization of left STACK and right HEAP memory throughout the article:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6aGxVkRq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u70jse15c9wzrt3je82w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6aGxVkRq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u70jse15c9wzrt3je82w.png" alt="Image description" width="800" height="415"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To understand copying in Javascript, we need to begin with what kind of type we are copying?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A Primitive and an Object.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Primitives are immutable, objects are mutable by default. This relates to the way we store the value in memory. &lt;/p&gt;

&lt;p&gt;With primitives we store the value on the Stack, while with objects, we store the value on the Heap. What is stored on the Stack, in the case of objects, is a pointer that refers (thus, the term &lt;em&gt;'reference'&lt;/em&gt;) to the memory address of the object value stored on the Heap.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Copying a primitive (Value type)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
let value = 3;
let valueCopy = value; // create copy

console.log(valueCopy); // 3

// Change valueCopy
valueCopy = 2
console.log(valueCopy); // 2

// ✅ Original NOT affected 
console.log(value); // 3

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Copying an array (Reference type)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let array1 = [1,2,3];
let array1Copy = array; // create copy

console.log(array1Copy); // [1,2,3];

// Change 1st element of the array
array1Copy[0] = 777;
console.log(array1Copy); // [ 777, 2, 3 ]

// ❌Original got affected
console.log(array1); // [ 777, 2, 3 ]


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

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;What we did above is just copy the pointer that points to the assigned memory slot in the Heap. Thus, traditional assignment via '=' results in an unwanted behavior. We need to copy the reference in Heap memory and create a whole new reference there.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;To achieve this we have two options: Shallow copy or Deep copy&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Shallow copy&lt;/strong&gt; &lt;br&gt;
&lt;em&gt;Def.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Deep copy&lt;/strong&gt; &lt;br&gt;
&lt;em&gt;Def.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Shallow copy&lt;/strong&gt; &lt;br&gt;
&lt;em&gt;Ex.&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
let array2 = [4,5,6];
let array2ShallowCopy = [...array2]; // create TRUE copy

console.log(array2ShallowCopy ); // [4,5,6];

// Change 1st element of the array
array2ShallowCopy [0] = 777;
console.log(array2ShallowCopy ); // [777,5,6]

// ✅ Original NOT affected 
console.log(array2); // [4,5,6]

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

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;The Shallow copy copies simple objects, meaning they have no nested objects within themselves.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Deep copy&lt;/strong&gt; &lt;br&gt;
&lt;em&gt;Ex.&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
let array3 = [7,[8],9];
let array3Copy = structuredClone(array3)); 

// Make some changes
array3Copy [0] = 777; // change shallow element
array3Copy [1][0] = 888; // change nested element
console.log(array3Copy ); // [ 777, [888], 9 ]

// ✅ Nested array NOT affected
console.log(array3); //  [7,[8],9]

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

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;The Deep Copy copies objects fully, however, nested they are.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;NB&lt;/strong&gt;&lt;br&gt;
structuredClone() is for objects that are serializable. If they are not serializable, it will fail in the same way that calling JSON.stringify() which was formerly used for deep copying.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Shallow vs Deep&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Imagine that nested objects form layers. If we have an array with an element that is also an array, we have 2 layers. A shallow copy means that only the top layer of the object is copied into a brand new memory slot on the HEAP. Any nested layer would be copied &lt;em&gt;'shallowly'&lt;/em&gt; - just as a reference address, without a whole new memory slot on the HEAP for the nested object.&lt;/p&gt;

&lt;p&gt;On the other hand, a deep copy makes a copy not only for the top layer, but for all nested layers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;As a rule of thumb, we could say that primitive values can only form a so called top layer. But if we include an object within our array, we automatically nest it as an element, creating a one more layer.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--0MV3E3UR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/or186668xmji5kiqal16.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--0MV3E3UR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/or186668xmji5kiqal16.png" alt="Image description" width="800" height="278"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Loose Coupling and Dependency Injection (DI) principle</title>
      <dc:creator>Vasil Vasilev</dc:creator>
      <pubDate>Tue, 11 Jul 2023 08:33:02 +0000</pubDate>
      <link>https://dev.to/vasilgvasilev/loose-coupling-and-dependency-injection-di-principle-3i8c</link>
      <guid>https://dev.to/vasilgvasilev/loose-coupling-and-dependency-injection-di-principle-3i8c</guid>
      <description>&lt;p&gt;&lt;strong&gt;What is the Dependency Injection (DI) principle?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The Dependency Injection principle is a software design pattern that promotes loose coupling and high modularity in object-oriented programming. &lt;br&gt;
With simple words, we provide dependencies to a class from the outside rather than create in the class itself.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Instead of this:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class UserService {

  logging(message) {
    console.log(message);
  }

  addUser(user) {
    // Add user logic...
    this.log(`User added: ${user}`);
  }
}


const userService = new UserService(); // Create the UserService

// Usage
userService.addUser("John Doe");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;We do this:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Logger class
class Logger {
  logging(message) {
    console.log(message);
  }
}

// UserService class with Logger dependency
class UserService {
  constructor(logger) {
    this.logger = logger;
  }

  addUser(user) {
    // Add user logic...
    this.logger.logging(`User added: ${user}`);
  }
}

// Creating instances and injecting dependencies

const logger = new Logger(); 
// Create a Logger instance

const userService = new UserService(logger); 
// Inject the Logger instance into UserService

// Usage
userService.addUser("John Doe");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The reason for such an abstraction is to achieve separations of concerns. We want our &lt;em&gt;addUser&lt;/em&gt; function to be part of our &lt;em&gt;UserServices&lt;/em&gt; class, but our &lt;em&gt;logging&lt;/em&gt; function being too fundamental to fix into only one class, should be abstracted away from &lt;em&gt;UserServices&lt;/em&gt; class into its own class. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why?&lt;/strong&gt; The answer is re-usability. Therefore, we abstract &lt;em&gt;logging&lt;/em&gt; function and inject it as a dependency via the constructor.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Constructor&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The constructor, thus, is a crucial tool since it not only initialises class properties but also serves as an entrypoint for its class' dependencies on other classes (the &lt;em&gt;UserService&lt;/em&gt; doesn't create a &lt;em&gt;Logger&lt;/em&gt; instance internally but relies on the &lt;em&gt;Logger&lt;/em&gt; instance provided to it).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We go from &lt;strong&gt;&lt;em&gt;thigh coupling&lt;/em&gt;&lt;/strong&gt; (logger function being an integral part of &lt;em&gt;UserService&lt;/em&gt; class) to &lt;strong&gt;&lt;em&gt;loose coupling&lt;/em&gt;&lt;/strong&gt; (The &lt;em&gt;Logger&lt;/em&gt; instance is independent of the &lt;em&gt;UserService&lt;/em&gt;, and we can easily replace it with a different &lt;em&gt;Logger&lt;/em&gt; implementation without modifying the &lt;em&gt;UserService&lt;/em&gt; code), thus, achieving reusability and abstraction.&lt;/p&gt;

</description>
      <category>coupling</category>
      <category>dependency</category>
      <category>injection</category>
    </item>
    <item>
      <title>Mutable And Immutable Values in Javascript</title>
      <dc:creator>Vasil Vasilev</dc:creator>
      <pubDate>Mon, 10 Jul 2023 18:48:10 +0000</pubDate>
      <link>https://dev.to/vasilgvasilev/mutable-and-immutable-values-in-javascript-1eho</link>
      <guid>https://dev.to/vasilgvasilev/mutable-and-immutable-values-in-javascript-1eho</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--AZmanLGd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m700y1lv2mtjv79shr7n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--AZmanLGd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m700y1lv2mtjv79shr7n.png" alt="Image description" width="800" height="480"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In JavaScript there are two types of data types - primitive types and objects. Whenever you define a variable, the JavaScript engine allocates a memory to it. It stores all variable names on the Stack, while the values are either on the Stack or on the Heap.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let str = "hello"; 
// str (variable name) is stored on the Stack
// 'hello' (value) is stored on the Stack

let obj = { fname: "Vasil", lname: "Vasilev"} 
// obj (variable name) is stored on the Stack
// {...} the value is stored on the Heap
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;NB: The { fname: "Vasil", lname: "Vasilev"}  is merely a reference which points to the actual value stored on the Heap.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Any data type value which is immutable is stored on a Stack data structure since it’s size is known during compilation phase.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mutable data types such as Objects, Arrays are stored on a Heap data structure and a reference to the Object or array is stored on the stack data structure.&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>mutable</category>
      <category>immutable</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Currying Step-By-Step</title>
      <dc:creator>Vasil Vasilev</dc:creator>
      <pubDate>Mon, 10 Jul 2023 17:06:14 +0000</pubDate>
      <link>https://dev.to/vasilgvasilev/currying-step-by-step-5eb2</link>
      <guid>https://dev.to/vasilgvasilev/currying-step-by-step-5eb2</guid>
      <description>&lt;p&gt;&lt;strong&gt;Definition&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Transform a function that takes multiple arguments into a series of functions that take a single argument each. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reason&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The main advantage of currying is that the new function can be partially applied to its arguments.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Instead of:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function sum(x, y, z) { 
    return x + y 
} 
sum(1, 2, 3); //LOGs: 6
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;We have:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function sum(x) { 
    return (y) =&amp;gt; { 
        return (z) =&amp;gt; { 
            return x + y + z;
        } 
    } 
} 
sum(1)(2)(3); //LOGs: 6
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Although currying can be achieved via other techniques, for example .bind(), this article focuses on utilizing closures. &lt;br&gt;
&lt;strong&gt;Closures enables us to allocate each closure for a returned function to a specific variable:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function sum(x) { 
    return (y) =&amp;gt; { 
        return (z) =&amp;gt; { 
            return x + y + z;
        } 
    } 
} 
const addOne = sum(1)
const addTwo = addOne(2)
console.log(addTwo(3)) //LOGs: 6
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;1.&lt;/strong&gt; When execution of the code comes to "const addOne = sum(1)", JS creates a closure for the returned function that captures the value of x as 1 in the Heap memory:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;In HEAP: x = 1

In Stack:
(y) =&amp;gt; { 
        return (z) =&amp;gt; { 
            return x(1) + y + z;
        } 
    } 

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2.&lt;/strong&gt; when execution of the code comes to "const addTwo = add(2)", JS creates a closure for the returned function that captures the value of y as 2 in the Heap memory:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;In HEAP: x = 1, y = 2

In Stack:
(z) =&amp;gt; { 
            return x(1) + y(2) + z;
        } 

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3.&lt;/strong&gt; when execution of the code comes to "console.log(addTwo(3))", JS creates a closure for the returned function that captures the value of z as 2 in the Heap memory:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;In HEAP: x = 1, y = 2, z = 3;

In Stack:
x(1) + y(2) + z(3);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All that is left is the execution of the final return:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function sum(1) { 
    return (2) =&amp;gt; { 
        return (3) =&amp;gt; { 
            return 1 + 2 + 3;
        } 
    } 
} 
const addOne = sum(1)
const addTwo = addOne(2)
console.log(addTwo(3)) //LOGs: 6
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>currying</category>
      <category>closure</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Why You Should Understand Closures To Master .reduce()</title>
      <dc:creator>Vasil Vasilev</dc:creator>
      <pubDate>Mon, 10 Jul 2023 14:30:46 +0000</pubDate>
      <link>https://dev.to/vasilgvasilev/why-you-need-to-understand-closures-to-fully-master-reduce-7ac</link>
      <guid>https://dev.to/vasilgvasilev/why-you-need-to-understand-closures-to-fully-master-reduce-7ac</guid>
      <description>&lt;p&gt;Although closures are one of the most potent features of Javascript, in my experience, they seem to be neglected in many explanations as if the reader is to infer what is under the hood on their own. If you look at a few articles about .reduce(), they may explain how we define it, the mechanism behind it, but not how it is possible for .reduce() to happen in the first place. This has proved especially irritating for me, in the beginning, since it left a feeling that I have to learn the concept by heart and I had to revisit the basic explanation after some time has passed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;So what is the basic definition?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.&lt;/em&gt; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What would a basic code example look like?&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let arr = [1, 2, 3];

const arrSum = arr.reduce(
    (totalOrAccumulator, currentValueToAddToTotalOrAccumulator) =&amp;gt; {
        totalOrAccumulator + currentValueToAddToTotalOrAccumulator
    }
)

console.log(arrSum)

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;The fundamental question is - how does .reduce() keep record of &lt;em&gt;totalOrAccumulator&lt;/em&gt;'s value during execution?&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The answer - closures.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;But before that we must take into account another &lt;em&gt;"oddity"&lt;/em&gt; with the code above.&lt;br&gt;
.reduce() is a higher-order function since it returns another function (callback fn), that being the one that actually has the parameters and the logic of accumulating the total value.&lt;/p&gt;

&lt;p&gt;This is a crucial point because closures provide a way for the callback function to maintain and update the state of the accumulator throughout the reduction process, resulting in the desired outcome.&lt;/p&gt;

&lt;p&gt;It is also a process that is hidden when implementing .reduce() and although that is a out of necessity for clean and succinct code, beginners may find it hard to wrap their head around what actually enables .reduce() to keep track of the total value (accumulator).&lt;/p&gt;

&lt;p&gt;It is hidden because the initial value is optional but it is the definite mark of closures in .reduce().&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;initialValue - mark of closures&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The following code is an example of reduce used with initialValue and it is a mark of closures, too, for the keen eye.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (accumulator, currentValue) =&amp;gt; accumulator + currentValue,
  initialValue
);

console.log(sumWithInitial);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Basic closure example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function closureFunction () {
    const number = 0;
    function addToNumber(addedNumber) {
        return number + addedNumber;
    }

    return addToNumber
}

const addFive = closureFunction();

console.log(addFive(5));

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

&lt;/div&gt;



&lt;p&gt;The code above reveals the fundamental parts of a closure:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;a higher-order function that returns another function&lt;/li&gt;
&lt;li&gt;a variable that is accessed by the returned function via lexical scoping&lt;/li&gt;
&lt;li&gt;explicit return of the returned function&lt;/li&gt;
&lt;li&gt;storing of the closure function in a variable&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The effect of the four steps above results in the greatest power of closures - we can access the variable stored in the closure function even after its execution. The reason for that is for a whole new article, but simply said, that variable (number in our case) is stored on the heap memory, not stack memory.&lt;/p&gt;

&lt;p&gt;Comparing the closure example and the .reduce() example with intialValue, we can clearly see how a variable maintains and updates the state of the accumulator throughout the reduction process.&lt;/p&gt;

</description>
      <category>closure</category>
      <category>reduce</category>
      <category>javascript</category>
    </item>
  </channel>
</rss>
