<?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: Rahul Sharma</title>
    <description>The latest articles on DEV Community by Rahul Sharma (@okrahul).</description>
    <link>https://dev.to/okrahul</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%2F729572%2Fe420908a-77c1-47b7-a058-355d866aa460.png</url>
      <title>DEV Community: Rahul Sharma</title>
      <link>https://dev.to/okrahul</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/okrahul"/>
    <language>en</language>
    <item>
      <title>Top Promise-Based Interview Coding Questions</title>
      <dc:creator>Rahul Sharma</dc:creator>
      <pubDate>Mon, 17 Nov 2025 12:14:15 +0000</pubDate>
      <link>https://dev.to/okrahul/top-promise-based-interview-coding-questions-3jgm</link>
      <guid>https://dev.to/okrahul/top-promise-based-interview-coding-questions-3jgm</guid>
      <description>&lt;p&gt;I’ve included &lt;strong&gt;questions + small hints&lt;/strong&gt; (not full solutions unless you want them).&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;1. What will be the output of this code?&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;A&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;B&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;C&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;&lt;strong&gt;Hint:&lt;/strong&gt; Think microtask queue vs sync.&lt;/p&gt;

&lt;p&gt;Expected order: A, C, B.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;2. Rewrite this callback code using Promises&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;getData&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;cb&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nf"&gt;setTimeout&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;cb&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;done&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Task:&lt;/strong&gt; Convert to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;a Promise&lt;/li&gt;
&lt;li&gt;async/await version&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;3. Create a function &lt;code&gt;delay(ms)&lt;/code&gt; that returns a Promise&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nf"&gt;delay&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;1 second passed&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;&lt;strong&gt;Hint:&lt;/strong&gt; Use &lt;code&gt;setTimeout&lt;/code&gt; + resolve.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;4. Implement &lt;code&gt;promisify&lt;/code&gt;&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Convert a callback-style function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;callback&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nf"&gt;callback&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;a&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;into:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;addPromise&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;promisify&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;add&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nf"&gt;addPromise&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Hint:&lt;/strong&gt; Resolve on success, reject on error.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;5. What is the output?&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;x&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Oops&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="k"&gt;catch&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;x&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Hint:&lt;/strong&gt; &lt;code&gt;.catch()&lt;/code&gt; returns a value → chain continues.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;6. Run promises in parallel and return results in order&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;tasks&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
  &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
  &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
  &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;];&lt;/span&gt;

&lt;span class="nf"&gt;runAll&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;tasks&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; 
&lt;span class="c1"&gt;// expected: [10, 20, 30]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Hint:&lt;/strong&gt; Use &lt;code&gt;Promise.all&lt;/code&gt;.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;7. Create a function that retries a Promise 3 times&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nf"&gt;retry&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;fetch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/api&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;catch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;error&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;Hint:&lt;/strong&gt; Loop + recursion + catch.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;8. Output prediction&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;test&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nf"&gt;test&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;4&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;Hint:&lt;/strong&gt; &lt;code&gt;await&lt;/code&gt; → microtask.&lt;/p&gt;

&lt;p&gt;Expected: 3, 1, 4, 2.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;9. Implement your own &lt;code&gt;Promise.all()&lt;/code&gt;&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Input:&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="nf"&gt;myPromiseAll&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="nx"&gt;p1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;p2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;p3&lt;/span&gt;&lt;span class="p"&gt;]).&lt;/span&gt;&lt;span class="nf"&gt;then&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;Hint:&lt;/strong&gt; Count resolved values + reject immediately.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;10. Difference between these two — output?&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;A&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;B&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;&lt;strong&gt;Hint:&lt;/strong&gt; Second one logs B immediately because you're calling the function.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;11. Chain Promises without using &lt;code&gt;.then()&lt;/code&gt;&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Given:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;f1&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="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;f2&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="mi"&gt;20&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;Call them one after another and sum the result.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;12. Why does this throw an error?&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;hello&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Hint:&lt;/strong&gt; Only allowed inside &lt;code&gt;async&lt;/code&gt; functions.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;13. Turn an array of URLs into fetched data (Promise + map)&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;urls&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;a.com&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;b.com&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;c.com&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;

&lt;span class="nf"&gt;fetchAll&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;urls&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Hint:&lt;/strong&gt; Map to fetch → Promise.all.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;14. Explain and predict output&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;reject&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;err&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="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;then&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="k"&gt;catch&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;catch&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="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;after catch&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;h2&gt;
  
  
  &lt;strong&gt;15. Create a timeout wrapper&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nf"&gt;timeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;fetch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/api&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="mi"&gt;2000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;catch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If Promise doesn’t resolve in 2 seconds → reject with timeout.&lt;/p&gt;




</description>
      <category>javascript</category>
      <category>interview</category>
      <category>challenge</category>
      <category>webdev</category>
    </item>
    <item>
      <title>The Ultimate Promise Deep Dive — Resolve, Reject, Then, and Async/Await Demystified</title>
      <dc:creator>Rahul Sharma</dc:creator>
      <pubDate>Mon, 17 Nov 2025 12:10:44 +0000</pubDate>
      <link>https://dev.to/okrahul/the-ultimate-promise-deep-dive-resolve-reject-then-and-asyncawait-demystified-1ml5</link>
      <guid>https://dev.to/okrahul/the-ultimate-promise-deep-dive-resolve-reject-then-and-asyncawait-demystified-1ml5</guid>
      <description>&lt;p&gt;Most developers don’t write raw Promises every day — we use tools like useQuery, axios, or helper libraries that wrap everything for us. But when it comes to debugging, reading polyfills, or understanding what those tools are actually doing, everything goes back to Promises.&lt;/p&gt;

&lt;p&gt;And especially today, when many beginners rely on AI to generate code, it's super important to truly understand what Promises are doing under the hood.&lt;/p&gt;

&lt;p&gt;So let’s start slow, simple, and clear. Step-by-step.— a zero-to-hero journey into JavaScript Promises. चलो शुरू करते हैं.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is a Promise? (I like this basic and deep definition of a Promise)
&lt;/h2&gt;

&lt;p&gt;A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.&lt;/p&gt;

&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Okay, so you’re here — which means either an interview is coming up soon, or you’re just genuinely curious about how Promises actually work. Both reasons are perfect.&lt;/p&gt;

&lt;p&gt;Before Promises, JavaScript handled async work using callbacks &lt;u&gt;(and yes, callbacks are still important in many real-world cases — we’ll cover that in a separate blog)&lt;/u&gt;. But back then, callbacks often led to messy, nested “callback hell.”&lt;/p&gt;

&lt;p&gt;Promises solved that problem, and later async/await made async code feel even smoother.&lt;/p&gt;

&lt;p&gt;We’ll go step by step — from &lt;strong&gt;basics to advance&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Exactly Is a Promise?
&lt;/h2&gt;

&lt;p&gt;A Promise is simply a placeholder for a value that you will receive in the future — not right now.&lt;br&gt;
The easiest way to imagine it is like ordering food at a restaurant:&lt;br&gt;
you get a token first, and the actual food (the value) comes later.&lt;/p&gt;

&lt;p&gt;A Promise can be in three states:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;pending → the async work is still happening&lt;/li&gt;
&lt;li&gt;fulfilled → the async work finished successfully&lt;/li&gt;
&lt;li&gt;rejected → the async work failed&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And once a Promise becomes fulfilled or rejected, its state is locked forever — it cannot change again.&lt;/p&gt;
&lt;h2&gt;
  
  
  Creating a Promise (executor, resolve, reject)
&lt;/h2&gt;

&lt;p&gt;To create a Promise, you use the new Promise() constructor.&lt;br&gt;
It takes a function (called the executor) with two arguments:&lt;/p&gt;

&lt;p&gt;resolve → call this when the async work succeeds&lt;br&gt;
reject → call this when something goes wrong&lt;/p&gt;

&lt;p&gt;Here’s the 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 myPromise = new Promise((resolve, reject) =&amp;gt; {
  // Simulating async work (like API call)
  setTimeout(() =&amp;gt; {
    const success = true; // change to false to test reject

    if (success) {
      resolve("Task completed!");
    } else {
      reject("Something went wrong!");
    }
  }, 1000);
});

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

&lt;/div&gt;



&lt;p&gt;This code creates a Promise that:&lt;br&gt;
waits 1 second&lt;br&gt;
then either resolves with "Task completed!"&lt;br&gt;
or rejects with "Something went wrong!"&lt;/p&gt;

&lt;p&gt;But creating a Promise alone does nothing —&lt;br&gt;
you must attach .then() / .catch() to use the result.&lt;/p&gt;
&lt;h2&gt;
  
  
  Consuming a Promise: then(), catch(), finally()
&lt;/h2&gt;

&lt;p&gt;Once you create a Promise, you need to “consume” it using:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;.then() → runs when the Promise is fulfilled (success)&lt;/li&gt;
&lt;li&gt;.catch() → runs when the Promise is rejected (failure)&lt;/li&gt;
&lt;li&gt;.finally() → always runs, success or failure&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here’s a simple example using the Promise we created earlier:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;myPromise
  .then((result) =&amp;gt; {
    console.log("Success:", result);
  })
  .catch((error) =&amp;gt; {
    console.log("Error:", error);
  })
  .finally(() =&amp;gt; {
    console.log("Promise done!");
  });

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

&lt;/div&gt;



&lt;p&gt;How this works:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If the Promise resolves → the code inside .then() runs&lt;/li&gt;
&lt;li&gt;If it rejects → the code inside .catch() runs&lt;/li&gt;
&lt;li&gt;And .finally() runs in both cases (cleanup, loaders, etc.)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Promise Chaining (How values flow)
&lt;/h2&gt;

&lt;p&gt;One of the best features of Promises is chaining — the output of one .then() becomes the input of the next .then().&lt;/p&gt;

&lt;p&gt;Think of it like passing a value step-by-step through a pipeline.&lt;/p&gt;

&lt;p&gt;Here’s a simple example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Promise.resolve(1)
  .then((num) =&amp;gt; {
    console.log("Step 1:", num); // 1
    return num + 1; // returns 2
  })
  .then((value) =&amp;gt; {
    console.log("Step 2:", value); // 2
    return value * 10; // returns 20
  })
  .then((finalValue) =&amp;gt; {
    console.log("Final Step:", finalValue); // 20
  });

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

&lt;/div&gt;



&lt;p&gt;✔ How it works:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The first .then() receives 1&lt;/li&gt;
&lt;li&gt;It returns 1 + 1 = 2&lt;/li&gt;
&lt;li&gt;The second .then() receives 2&lt;/li&gt;
&lt;li&gt;It returns 2 * 10 = 20&lt;/li&gt;
&lt;li&gt;The last .then() receives 20
**
Every .then() creates a new Promise internally, making chaining possible.**&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;🔥 Important:&lt;/p&gt;

&lt;p&gt;If you don’t return anything inside a .then(), the next .then() receives undefined. &lt;u&gt;(Good for interview question)&lt;/u&gt;&lt;/p&gt;

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

&lt;h2&gt;
  
  
  Error Handling in Promises
&lt;/h2&gt;

&lt;p&gt;Errors in Promises work in a very simple way:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If any .then() throws an error → the chain jumps to .catch().&lt;/li&gt;
&lt;li&gt;After a .catch(), the chain continues normally (unless you re-throw).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here’s a clean example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Promise.resolve("Start")
  .then((val) =&amp;gt; {
    console.log(val); // Start
    throw new Error("Something broke!");
  })
  .then(() =&amp;gt; {
    // This will NOT run
    console.log("This will be skipped");
  })
  .catch((err) =&amp;gt; {
    console.log("Caught:", err.message); // Caught: Something broke!
  })
  .then(() =&amp;gt; {
    console.log("Chain continues after catch"); 
  });

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

&lt;/div&gt;



&lt;p&gt;✔ What’s happening?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The first .then() runs → prints "Start"&lt;/li&gt;
&lt;li&gt;It throws an error&lt;/li&gt;
&lt;li&gt;The chain skips all other .then() and jumps to .catch()&lt;/li&gt;
&lt;li&gt;After .catch(), the chain continues with the next .then()&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;🔥 Bonus Tip&lt;/p&gt;

&lt;p&gt;If you re-throw inside .catch(), the error will go to the next .catch().&lt;/p&gt;

&lt;p&gt;Here you go — &lt;a href="https://dev.to/okrahul/top-promise-based-interview-coding-questions-3jgm"&gt;a solid list of Promise-based interview coding questions.&lt;/a&gt;&lt;br&gt;
These are the ones asked most commonly in frontend + JS rounds, and perfect for devs who preparing for interviews.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>performance</category>
      <category>javascript</category>
      <category>basic</category>
    </item>
    <item>
      <title>Real-Time Updates in Web Apps: Why I Chose SSE Over WebSockets</title>
      <dc:creator>Rahul Sharma</dc:creator>
      <pubDate>Mon, 05 May 2025 20:16:02 +0000</pubDate>
      <link>https://dev.to/okrahul/real-time-updates-in-web-apps-why-i-chose-sse-over-websockets-k8k</link>
      <guid>https://dev.to/okrahul/real-time-updates-in-web-apps-why-i-chose-sse-over-websockets-k8k</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl4ggp46nziqtkv9j0kk1.webp" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl4ggp46nziqtkv9j0kk1.webp" alt="Image pragmaticpineapple" width="800" height="600"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Modern web apps need &lt;strong&gt;real-time communication&lt;/strong&gt;—whether it's a chat app, stock ticker, or live sports commentary. There are multiple ways to implement it:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;HTTP Polling&lt;/li&gt;
&lt;li&gt;WebSockets&lt;/li&gt;
&lt;li&gt;Server-Sent Events (SSE)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this blog, I’ll walk you through why I picked &lt;strong&gt;SSE&lt;/strong&gt; for my commentary app, how it works, and how you can implement it using &lt;strong&gt;React&lt;/strong&gt; and &lt;strong&gt;Node.js&lt;/strong&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;First, let’s understand that all the methods we use for real-time updates—Polling, WebSockets, and SSE—are based on the principles of Event-Driven Architecture (EDA). So before comparing them, it's important to know what EDA is and how it shapes real-time communication.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;🧠 What is Event-Driven Architecture?&lt;br&gt;
Event-Driven Architecture (EDA) is a design pattern where components of a system communicate through events. Instead of continuously requesting information, the system reacts to changes or triggers. For example, when a server emits a new event (like a notification), the frontend listens and responds to it—no need for repeated polling.&lt;/p&gt;

&lt;p&gt;➡️ Want to dive deeper? Read this guide on &lt;a href="https://www.geeksforgeeks.org/event-driven-architecture-system-design/" rel="noopener noreferrer"&gt;Event-Driven Architecture&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Real-Time Communication Methods (With Examples)
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. &lt;strong&gt;HTTP Polling&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;What it is:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The client (frontend) sends HTTP requests at regular intervals (e.g., every 5 seconds) to check for updates on the server. The server responds with the latest data or status.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When to use it:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When real-time accuracy is important but &lt;strong&gt;you don't need instant updates&lt;/strong&gt;, or when &lt;strong&gt;server push&lt;/strong&gt; is not available.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example use case:&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;✅ Checking UPI Payment Status:&lt;/p&gt;

&lt;p&gt;When a user initiates a UPI payment, the frontend may not immediately know if the payment was successful.&lt;/p&gt;

&lt;p&gt;So, the client sends a request to the server every few seconds to check the status. Once the server confirms that the payment is successful, the frontend can stop polling.&lt;/p&gt;


&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;js
CopyEdit
// Polling example (client-side - pseudocode)
setInterval(() =&amp;gt; {
  fetch('/api/payment-status')
    .then(res =&amp;gt; res.json())
    .then(data =&amp;gt; {
      if (data.status === 'success') {
        clearInterval(this);
        alert('Payment Successful!');
      }
    });
}, 5000); // Poll every 5 seconds
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;In the real world, we implement webhooks for payment confirmation, which involve server-to-server communication. However, in my case, I implemented a client-to-server approach, so HTTP polling would work.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  2. &lt;strong&gt;WebSockets&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;What it is:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;WebSocket is a full-duplex communication channel over a single long-lived connection. Both the &lt;strong&gt;client and server&lt;/strong&gt; can send and receive data anytime after the connection is established.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When to use it:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When you need &lt;strong&gt;two-way communication&lt;/strong&gt;, like real-time chat, collaborative tools (e.g., Google Docs), or multiplayer games.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example use case:&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;🧑‍💬 Live Chat Application:&lt;/p&gt;

&lt;p&gt;A chat app where both users can send and receive messages in real time. When one user sends a message, the other receives it instantly without refreshing or polling.&lt;/p&gt;


&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;js
CopyEdit
// Client-side WebSocket example
const socket = new WebSocket('wss://your-chat-app.com/socket');

socket.onopen = () =&amp;gt; {
  socket.send(JSON.stringify({ type: 'message', text: 'Hello!' }));
};

socket.onmessage = (event) =&amp;gt; {
  const data = JSON.parse(event.data);
  console.log('Received message:', data.text);
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. &lt;strong&gt;Server-Sent Events (SSE)&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;What it is:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;SSE allows the &lt;strong&gt;server to push real-time updates to the client&lt;/strong&gt; over a single long-lived HTTP connection. Unlike WebSockets, communication is &lt;strong&gt;one-way&lt;/strong&gt; (server → client only).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When to use it:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When the server needs to &lt;strong&gt;send continuous updates&lt;/strong&gt;, like in dashboards, notifications, or live commentary apps—&lt;strong&gt;without requiring the client to ask&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example use case:&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;🏏 Live Sports Commentary Feed:&lt;/p&gt;

&lt;p&gt;A sports web app needs to show new commentary updates as they happen. The server sends updates automatically using SSE, and the frontend displays them instantly.&lt;/p&gt;


&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;js
CopyEdit
// Client-side using EventSource
const eventSource = new EventSource('/events');

eventSource.onmessage = (event) =&amp;gt; {
  const data = JSON.parse(event.data);
  console.log('New update:', data.comment);
};

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

&lt;/div&gt;



&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Method&lt;/th&gt;
&lt;th&gt;Direction&lt;/th&gt;
&lt;th&gt;Connection&lt;/th&gt;
&lt;th&gt;Browser Support&lt;/th&gt;
&lt;th&gt;Use Case&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;HTTP Polling&lt;/td&gt;
&lt;td&gt;Client → Server&lt;/td&gt;
&lt;td&gt;Repeated&lt;/td&gt;
&lt;td&gt;✅ All browsers&lt;/td&gt;
&lt;td&gt;Simple but inefficient&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;WebSockets&lt;/td&gt;
&lt;td&gt;Two-way&lt;/td&gt;
&lt;td&gt;Persistent&lt;/td&gt;
&lt;td&gt;✅ Requires setup&lt;/td&gt;
&lt;td&gt;Chat, multiplayer games&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;SSE&lt;/td&gt;
&lt;td&gt;Server → Client&lt;/td&gt;
&lt;td&gt;Persistent&lt;/td&gt;
&lt;td&gt;✅ Native (EventSource)&lt;/td&gt;
&lt;td&gt;Live feed, notifications&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  Why I Chose SSE for My Commentary App
&lt;/h2&gt;

&lt;p&gt;There are multiple ways to implement real-time updates in modern web applications. You can choose from WebSockets, HTTP Polling, and Server-Sent Events (SSE)—each with its own pros and cons.&lt;/p&gt;

&lt;p&gt;In my case, I only needed unidirectional communication (from server to client), and I wanted a lightweight and easy-to-implement solution. That's why SSE was the perfect fit for my use case.&lt;/p&gt;

&lt;p&gt;I recently built a sports commentary app where the server pushes live updates (like match events) to the frontend. With SSE, the browser maintains a connection to the server using the built-in &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/EventSource" rel="noopener noreferrer"&gt;EventSource&lt;/a&gt; API and receives updates without needing constant polling or a full WebSocket setup.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;One-way communication (server → client)&lt;/li&gt;
&lt;li&gt;Simple setup without installing extra libraries&lt;/li&gt;
&lt;li&gt;Browser-native support&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;👉 Check out the &lt;a href="https://github.com/okrahul/SSE-live-notification" rel="noopener noreferrer"&gt;GitHub repository&lt;/a&gt; here. Feel free to ⭐️ the repo if you find it useful!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;SSE checked all the boxes! I used EventSource on the frontend and Express on the backend.&lt;/p&gt;

&lt;h2&gt;
  
  
  🔧 Boosting SSE with Pub/Sub (Redis, Kafka, etc.)
&lt;/h2&gt;

&lt;p&gt;SSE works great on its own for small apps. But when you need to scale across multiple servers or services, you can connect it to a pub/sub system like:&lt;/p&gt;

&lt;p&gt;Redis (simple, in-memory pub/sub)&lt;/p&gt;

&lt;p&gt;Kafka (great for distributed systems and large data streams)&lt;/p&gt;

&lt;p&gt;This way, your backend can listen to events from Redis/Kafka and forward them to connected clients via SSE.&lt;/p&gt;

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

&lt;p&gt;SSE is often underrated but powerful for use cases like notifications, newsfeeds, or live commentary.&lt;/p&gt;

&lt;p&gt;You don’t always need complex WebSocket setups. Sometimes, simple is better.&lt;/p&gt;

&lt;p&gt;Choose your real-time tool based on your app's requirements—not just what's trendy.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Follow me on &lt;a href="https://dev.to/okrahul"&gt;okrahul&lt;/a&gt; to stay connected with the developer community! Check out my recent blogs—they're packed with valuable insights. If you have any questions or doubts, feel free to drop a comment!&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>javascript</category>
      <category>serversentevents</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Injecting Environment Variables in a Deployed React App Without Rebuilding.</title>
      <dc:creator>Rahul Sharma</dc:creator>
      <pubDate>Tue, 04 Feb 2025 12:34:54 +0000</pubDate>
      <link>https://dev.to/okrahul/injecting-environment-variables-in-a-deployed-react-app-without-rebuilding-1524</link>
      <guid>https://dev.to/okrahul/injecting-environment-variables-in-a-deployed-react-app-without-rebuilding-1524</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1qmf8bzs7iuq6ne6worg.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1qmf8bzs7iuq6ne6worg.jpg" alt="Image banner" width="800" height="392"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Environment Variables Matter in React Apps
&lt;/h2&gt;

&lt;p&gt;Environment variables play a crucial role in frontend applications, allowing developers to configure settings without modifying the actual code. They are commonly used to store:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;API base URLs&lt;/strong&gt; – To connect with different backend services.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Feature flags&lt;/strong&gt; – To enable or disable specific features dynamically.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Authentication keys&lt;/strong&gt; – To manage secure access to APIs.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Third-party service configurations&lt;/strong&gt; – For analytics, payment gateways, etc.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By using environment variables, we can keep sensitive information out of the codebase and easily manage different configurations for development, staging, and production environments.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Common Issue: Rebuilding After Changing .env Variables
&lt;/h2&gt;

&lt;p&gt;React applications (built with Create React App, Vite, or similar tools) inject environment variables at &lt;strong&gt;build time&lt;/strong&gt;. This means:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If you modify an environment variable in the &lt;code&gt;.env&lt;/code&gt; file, the changes &lt;strong&gt;won’t&lt;/strong&gt; take effect until you rebuild the project using &lt;code&gt;npm run build&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;In production, changing something like an &lt;strong&gt;API URL&lt;/strong&gt; or a &lt;strong&gt;feature flag&lt;/strong&gt; requires a &lt;strong&gt;complete rebuild and redeployment&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This can be a problem in dynamic environments where configurations change frequently.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why This is a Problem in Production
&lt;/h2&gt;

&lt;p&gt;Imagine you’ve deployed a React app, and:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Your API URL changes based on the &lt;strong&gt;region&lt;/strong&gt; where the user is located.&lt;/li&gt;
&lt;li&gt;You want to &lt;strong&gt;toggle a feature flag&lt;/strong&gt; without redeploying the entire frontend.&lt;/li&gt;
&lt;li&gt;You’re using a &lt;strong&gt;CI/CD pipeline&lt;/strong&gt; and need flexibility in setting environment variables at runtime.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Since React builds are static, you’re forced to rebuild the entire project just to update a configuration.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Need for Runtime Environment Variables
&lt;/h2&gt;

&lt;p&gt;Unlike backend applications (like &lt;strong&gt;Node.js&lt;/strong&gt;), frontend React apps don’t naturally support runtime environment variables. This is because React is a &lt;strong&gt;static application&lt;/strong&gt; once built, meaning the JavaScript files don’t change unless you rebuild them.&lt;/p&gt;

&lt;p&gt;To solve this problem, we can use &lt;strong&gt;runtime environment variables&lt;/strong&gt;, allowing us to update configurations &lt;strong&gt;without rebuilding the React app&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  How Backend Frameworks Handle Environment Variables Differently
&lt;/h2&gt;

&lt;p&gt;Backend frameworks (like Node.js) handle environment variables &lt;strong&gt;at runtime&lt;/strong&gt;. Instead of being hardcoded during build time, they are accessed dynamically using &lt;code&gt;process.env&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Example in a Node.js backend:&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="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;express&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;require&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;express&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;app&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;express&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/api/config&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;req&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;json&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;apiUrl&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;env&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;API_URL&lt;/span&gt; &lt;span class="p"&gt;});&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;listen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;4000&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Server running on port 4000&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;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we can change the &lt;code&gt;API_URL&lt;/code&gt; environment variable &lt;strong&gt;without restarting or redeploying&lt;/strong&gt; the application.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to Inject Environment Variables at Runtime in a React App
&lt;/h2&gt;

&lt;p&gt;Since React itself doesn’t support runtime environment variables, we can solve this by using a &lt;strong&gt;Node.js server&lt;/strong&gt; to inject environment variables dynamically.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 1: Create a &lt;code&gt;server.js&lt;/code&gt; File
&lt;/h3&gt;

&lt;p&gt;We will use &lt;strong&gt;Express.js&lt;/strong&gt; to serve the React app and dynamically generate a configuration file.&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="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;express&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;require&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;express&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;path&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;require&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;path&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;dns&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;require&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;dns&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;app&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;express&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="c1"&gt;// Path to the React build folder&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;staticDir&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;path&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;__dirname&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;dist&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Serving static files from:&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;staticDir&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;use&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;express&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;static&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;staticDir&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;

&lt;span class="c1"&gt;// Dynamic environment variable injection&lt;/span&gt;
&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/config.js&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;req&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;dns&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;lookup&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;env&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;VITE_CORE_ENGINE_IP&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;err&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;address&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;err&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;DNS lookup failed:&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;err&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
      &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;status&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;500&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;window.ENV = { error: 'DNS lookup failed' }; &lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Resolved address:&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;address&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setHeader&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Content-Type&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;application/javascript&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;`
      window._ENV_ = {
        VITE_CORE_ENGINE_IP: "&lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;address&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;",
        VITE_CONFIG_PATH: "&lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;env&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;VITE_CONFIG_PATH&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&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="c1"&gt;// React Router fallback&lt;/span&gt;
&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;*&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;req&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sendFile&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;path&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;staticDir&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;index.html&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="c1"&gt;// Start the server&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;PORT&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;env&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;PORT&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="mi"&gt;4000&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;listen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;PORT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;`Server running on http://localhost:&lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;PORT&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&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;h3&gt;
  
  
  How This Works:
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Serving Static Files:&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;express.static(staticDir)&lt;/code&gt; serves the built React files from the &lt;code&gt;dist/&lt;/code&gt; folder.&lt;/li&gt;
&lt;li&gt;This makes the frontend accessible like a normal static website.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Injecting Runtime Environment Variables:&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;/config.js&lt;/code&gt; endpoint generates a &lt;strong&gt;JavaScript file dynamically&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;It fetches values from &lt;code&gt;process.env&lt;/code&gt; &lt;strong&gt;at runtime&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;These values are injected into a &lt;code&gt;window._ENV_&lt;/code&gt; object that React can read.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;DNS Resolution for Dynamic IPs:&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;dns.lookup()&lt;/code&gt; function resolves the backend service IP dynamically.&lt;/li&gt;
&lt;li&gt;This is useful when running in &lt;strong&gt;Docker&lt;/strong&gt; or &lt;strong&gt;Kubernetes&lt;/strong&gt;, where backend services may have changing IPs.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;React Router Fallback:&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;app.get("*")&lt;/code&gt; ensures React handles routing properly.&lt;/li&gt;
&lt;li&gt;This prevents 404 errors when users navigate to different routes.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Step 2: Build the Docker Image
&lt;/h2&gt;

&lt;p&gt;To package the application, create a &lt;strong&gt;Dockerfile&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;FROM node:16
WORKDIR /app
COPY . .
RUN npm install &amp;amp;&amp;amp; npm run build
CMD ["node", "server.js"]

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

&lt;/div&gt;



&lt;p&gt;Then, build the image:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker build -t my-react-app .

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 3: Run the Docker Container with Environment Variables
&lt;/h2&gt;

&lt;p&gt;Now, run the container with dynamic environment variables:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker run -p 4000:4000 -e VITE_CORE_ENGINE_IP=192.168.1.100 -e VITE_CONFIG_PATH=/new-path my-react-app

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Benefits of Using Runtime Environment Variables
&lt;/h2&gt;

&lt;p&gt;✅ &lt;strong&gt;No Need to Rebuild the React App&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The frontend dynamically fetches configuration values &lt;strong&gt;without a rebuild&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Updates to API URLs or feature flags take effect instantly.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;✅ &lt;strong&gt;Easier Deployment and CI/CD&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The same frontend build works across &lt;strong&gt;staging&lt;/strong&gt;, &lt;strong&gt;production&lt;/strong&gt;, etc.&lt;/li&gt;
&lt;li&gt;No need to maintain multiple builds for different environments.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;✅ &lt;strong&gt;Handles Dynamic Configurations&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Useful for applications with &lt;strong&gt;auto-scaling&lt;/strong&gt;, &lt;strong&gt;dynamic IPs&lt;/strong&gt;, or &lt;strong&gt;third-party integrations&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Alternative: Using Nginx for Deployment
&lt;/h2&gt;

&lt;p&gt;If you are using &lt;strong&gt;Nginx&lt;/strong&gt; for deploying your React app, you can achieve the same effect &lt;strong&gt;without extra configuration&lt;/strong&gt;. Instead of serving the app via a Node.js server, you can configure Nginx to serve static files and inject environment variables at runtime. In my case, I initially used the Node.js server approach, but later, we decided to go with Nginx, which simplified the deployment process.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 1: Build the Docker Image
&lt;/h2&gt;

&lt;p&gt;To package the application, create a &lt;strong&gt;Dockerfile&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;FROM node:16
WORKDIR /app
COPY . .
RUN npm install &amp;amp;&amp;amp; npm run build
CMD ["node", "server.js"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, build the image:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker build -t my-react-app .
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 2: Run the Docker Container with Environment Variables
&lt;/h2&gt;

&lt;p&gt;Now, run the container with dynamic environment variables:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker run -p 4000:4000 -e VITE_CORE_ENGINE_IP=192.168.1.100 -e VITE_CONFIG_PATH=/new-path my-react-app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;p&gt;Injecting runtime environment variables in a React app &lt;strong&gt;without rebuilding&lt;/strong&gt; can save time and effort in production. Whether using a &lt;strong&gt;Node.js server&lt;/strong&gt; or &lt;strong&gt;Nginx&lt;/strong&gt;, this approach makes deployments more flexible and maintainable.&lt;/p&gt;

&lt;p&gt;This approach is especially useful for &lt;strong&gt;CI/CD pipelines&lt;/strong&gt;, &lt;strong&gt;microservices&lt;/strong&gt;, and &lt;strong&gt;dynamic configurations&lt;/strong&gt;, making it an excellent solution for modern frontend applications.&lt;/p&gt;

&lt;p&gt;🚀 &lt;strong&gt;Now, you can change your configurations without worrying about rebuilding your entire app!&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>devops</category>
      <category>node</category>
      <category>docker</category>
    </item>
    <item>
      <title>Understanding Node.js: Event-Driven Architecture and Non-Blocking I/O Model</title>
      <dc:creator>Rahul Sharma</dc:creator>
      <pubDate>Tue, 22 Oct 2024 11:19:33 +0000</pubDate>
      <link>https://dev.to/okrahul/understanding-nodejs-event-driven-architecture-and-non-blocking-io-model-3358</link>
      <guid>https://dev.to/okrahul/understanding-nodejs-event-driven-architecture-and-non-blocking-io-model-3358</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1btgqevut173ehyzkp55.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1btgqevut173ehyzkp55.png" alt="banner1" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In our last blog, we looked at the basics of Node.js and why it’s important for server-side development. In this post, we will dive deeper into Node.js architecture, focusing on two important concepts: event-driven architecture and the non-blocking I/O model. These ideas are key to understanding how Node.js can handle many tasks at once and run efficiently. The event-driven model allows Node.js to manage multiple operations without slowing down, while the non-blocking I/O model lets it work on tasks without waiting for them to finish. Let’s break these concepts down in simple terms to see how Node.js really works.&lt;/p&gt;

&lt;h3&gt;
  
  
  Event-Driven Architecture
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Event-Driven Architecture&lt;/strong&gt; is a way of designing applications where the flow of the program is guided by events—things that happen, like a user clicking a button or receiving a message. In this setup, the application waits for events to occur and then responds to them using special functions called event handlers. This approach makes applications more flexible and responsive because they can react to real-time changes without getting stuck. In Node.js, this event-driven model is key to handling many tasks at once, allowing it to efficiently manage multiple users and connections.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa9fot7zp2cp5y4pw8fjp.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa9fot7zp2cp5y4pw8fjp.jpg" alt="event-driven" width="600" height="252"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: I know it can be a bit difficult to understand on the first read, so let’s look at a very simple example.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;An &lt;strong&gt;event-driven&lt;/strong&gt; model is like a "cause and effect" system.&lt;/p&gt;

&lt;p&gt;Imagine you're hosting a party. Whenever someone rings the doorbell (the event), you open the door (the action). You don’t stand by the door waiting for someone to arrive all the time—you just respond when the doorbell rings. In the meantime, you’re free to do other things, like serve snacks or chat with guests.&lt;/p&gt;

&lt;p&gt;In programming, &lt;strong&gt;event-driven&lt;/strong&gt; means the system doesn't wait around for tasks to finish. Instead, it responds to events (like a user clicking a button or data being received) and takes action when needed. This way, the system stays free to handle other tasks while waiting for events to happen.&lt;/p&gt;

&lt;p&gt;This is how Node.js works—it responds to events when they happen, which makes it efficient and able to handle multiple things at once.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Non-Blocking I/O Model&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;non-blocking I/O model&lt;/strong&gt; is a programming approach that allows applications to perform input and output operations without waiting for them to complete before moving on to the next task. In this model, when a request is made (such as reading from a file or making a network call), the application continues executing other code while waiting for the response. This is achieved through asynchronous operations and the event loop, which enables the system to efficiently manage multiple tasks simultaneously. As a result, the non-blocking I/O model enhances application performance and responsiveness, making it ideal for scenarios with high user interactions or real-time data processing.&lt;/p&gt;

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

&lt;blockquote&gt;
&lt;p&gt;Note: I also have an example to explain this in very simple language.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Non-blocking I/O&lt;/strong&gt; is like multitasking without getting stuck.&lt;/p&gt;

&lt;p&gt;Imagine you're at a restaurant, and you place an order with the waiter. Instead of standing there waiting for your food to be ready, the waiter takes other orders, serves drinks, or chats with customers while your food is being prepared in the kitchen. Once your food is ready, the kitchen notifies the waiter, and they bring it to you.&lt;/p&gt;

&lt;p&gt;In programming, &lt;strong&gt;non-blocking I/O&lt;/strong&gt; works the same way. Instead of waiting for one task (like reading a file or getting data from a database) to finish before moving on to the next task, the system keeps working on other things. When the task is done, it comes back to handle the result. This makes the system fast and efficient, allowing it to manage many tasks at the same time without getting "blocked" by any one of them.&lt;/p&gt;

&lt;h3&gt;
  
  
  Advantages of Event-Driven, Non-Blocking I/O
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Scalability&lt;/strong&gt;: Node.js excels at handling numerous concurrent connections efficiently thanks to its non-blocking architecture. This makes it an ideal choice for building high-performance applications that can scale with increasing user demand.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Responsiveness&lt;/strong&gt;: The event-driven model enables Node.js to quickly respond to incoming events, significantly enhancing the responsiveness of applications. Users experience smoother interactions, as the system can promptly handle actions like clicks or data requests.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Resource Efficiency&lt;/strong&gt;: By avoiding blockage of the event loop, Node.js optimizes the use of system resources. This leads to a reduced memory footprint and increased overall throughput, allowing applications to perform more tasks simultaneously without overwhelming the system.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Event Loop
&lt;/h2&gt;

&lt;p&gt;The event loop is a key part of Node.js that helps it handle tasks efficiently using an event-driven approach and non-blocking I/O. It constantly checks for tasks to execute, like incoming requests or user actions. When an asynchronous task, such as reading a file or making a network request, starts, Node.js offloads that task so the main thread can keep working on other things without waiting. This non-blocking behavior allows Node.js to manage multiple tasks at once. Once the asynchronous task is finished, the event loop picks it up and runs the callback function. By using this event-driven and non-blocking system, Node.js delivers high performance and responsiveness, making it great for real-time applications and those with many users.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;If you have any doubts or confusion about the JavaScript event loop and the Node.js event loop, here I will explain the differences.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Node.js Event Loop vs. JavaScript Event Loop
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Environment&lt;/strong&gt;:

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Node.js Event Loop&lt;/strong&gt;: Operates in a server-side environment, handling asynchronous I/O tasks like file operations and network requests.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;JavaScript Event Loop&lt;/strong&gt;: Functions in web browsers, managing user interactions and DOM updates.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Purpose&lt;/strong&gt;:

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Node.js Event Loop&lt;/strong&gt;: Optimized for server tasks, enabling scalable web applications by efficiently managing multiple requests simultaneously.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;JavaScript Event Loop&lt;/strong&gt;: Focuses on keeping web pages responsive by handling events triggered by user actions.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Task Handling&lt;/strong&gt;:

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Node.js Event Loop&lt;/strong&gt;: Utilizes a callback queue and prioritizes tasks based on type, allowing for efficient execution of I/O operations with libraries like &lt;code&gt;libuv&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;JavaScript Event Loop&lt;/strong&gt;: Typically has a simpler model with a single callback queue, processing tasks in the order they arrive.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Concurrency Model&lt;/strong&gt;:

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Node.js Event Loop&lt;/strong&gt;: Supports high concurrency, allowing many simultaneous connections without blocking the main thread.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;JavaScript Event Loop&lt;/strong&gt;: Handles concurrency through the browser’s capabilities, primarily focusing on executing scripts and managing UI events.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In essence, both event loops manage asynchronous tasks but are tailored for different environments—Node.js for server-side applications and JavaScript for client-side interactions.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;Important!!&lt;br&gt;
&lt;code&gt;In my upcoming posts, I'll be diving into key topics around Node.js and JavaScript, breaking them down in a way that's simple and easy to grasp—so you can understand them with just one read! 😊 I'm always open to your questions, as I'm still learning too. Your queries help me grow and dive deeper into the topics I cover, so let's learn together. 🙌 Thanks for all your support and for enjoying the content!&lt;/code&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>node</category>
      <category>webdev</category>
      <category>programming</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Introduction to Node.js: What is Node.js and Why Use It?</title>
      <dc:creator>Rahul Sharma</dc:creator>
      <pubDate>Fri, 18 Oct 2024 11:41:23 +0000</pubDate>
      <link>https://dev.to/okrahul/introduction-to-nodejs-what-is-nodejs-and-why-use-it-275n</link>
      <guid>https://dev.to/okrahul/introduction-to-nodejs-what-is-nodejs-and-why-use-it-275n</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnkocitw4vgpo8x9zp1q0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnkocitw4vgpo8x9zp1q0.png" alt="banner one" width="800" height="533"&gt;&lt;/a&gt; 1. &lt;strong&gt;Introduction&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In web development, you typically have two sides to every application: the client-side (frontend) and the server-side (backend). The client-side is what users interact with in their browsers—the visual elements like buttons, forms, and text. On the other hand, the server-side is where the magic happens behind the scenes. It handles tasks like storing data, processing user requests, and communicating with databases.&lt;/p&gt;

&lt;p&gt;Traditionally, server-side development has been done using languages like PHP, Ruby, Python, or Java. Each of these languages requires its own runtime environment and typically involves complex, multi-threaded processes to handle multiple requests at once.&lt;/p&gt;

&lt;p&gt;Node.js allows developers to use JavaScript on the server-side, not just the frontend. Its event-driven, non-blocking design makes it fast and efficient, ideal for handling multiple tasks at once. With Node.js, you can use the same language for both the frontend and backend, making development simpler and more streamlined.&lt;/p&gt;




&lt;h3&gt;
  
  
  What is Node.js?
&lt;/h3&gt;

&lt;p&gt;Node.js is a runtime environment that allows developers to run JavaScript on the server-side, not just in the browser. Traditionally, JavaScript was used only for frontend tasks, but with Node.js, you can use it to build server-side applications. This makes Node.js different from other backend technologies like PHP, Python, or Ruby, which use different languages for server-side programming.&lt;/p&gt;

&lt;p&gt;With Node.js, you can easily build fast, scalable applications, thanks to its modern architecture and powerful JavaScript engine.&lt;/p&gt;

&lt;h3&gt;
  
  
  Node.js: Single-Threaded, Event-Driven Model
&lt;/h3&gt;

&lt;p&gt;Unlike traditional backend systems that use multiple threads (like many workers) to handle multiple tasks at once, &lt;strong&gt;Node.js&lt;/strong&gt; works differently. It uses a &lt;strong&gt;single-threaded, event-driven model&lt;/strong&gt;, meaning it has just one main thread to handle tasks. But here’s the magic: it doesn’t get stuck waiting for one task to finish before moving on to the next. Instead, it uses events to manage tasks efficiently.&lt;/p&gt;

&lt;p&gt;For example, if Node.js is waiting for data from a database, it doesn’t sit idle. It moves on to handle other requests in the meantime and comes back when the data is ready. This is called &lt;strong&gt;non-blocking&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Even though it’s single-threaded, Node.js can still handle many tasks at once without slowing down, which makes it perfect for real-time applications or tasks that need to manage lots of requests simultaneously.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;To learn more about how Node.js handles multiple tasks efficiently, check out topics like the &lt;strong&gt;&lt;em&gt;Event Loop, Callbacks, and Asynchronous Programming&lt;/em&gt;&lt;/strong&gt;. These concepts are key to understanding the full power of Node.js.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h3&gt;
  
  
  How to Create a Simple Server in Node.js
&lt;/h3&gt;

&lt;p&gt;Let’s create a basic web server using Node.js:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Install Node.js&lt;/strong&gt; (if you haven’t already). You can download it from &lt;a href="https://nodejs.org" rel="noopener noreferrer"&gt;nodejs.org&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Create a JavaScript file&lt;/strong&gt;, for example &lt;code&gt;server.js&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Write the code&lt;/strong&gt; to set up a simple server.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here’s the code for a simple server:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Import the built-in 'http' module&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;http&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;require&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;http&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// Create a server&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;server&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;http&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;createServer&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;req&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;statusCode&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// Set the status code to 200 (OK)&lt;/span&gt;
  &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setHeader&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Content-Type&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;text/plain&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Set the content type to plain text&lt;/span&gt;
  &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;end&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Hello, World!&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Send a response to the client&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="c1"&gt;// Define the port for the server to listen on&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;port&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;3000&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nx"&gt;server&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;listen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;port&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;`Server running at http://localhost:&lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;port&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&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;ol&gt;
&lt;li&gt;
&lt;strong&gt;Run the server&lt;/strong&gt; by opening your terminal and typing:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;node server.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Access the server&lt;/strong&gt; by going to &lt;code&gt;http://localhost:3000/&lt;/code&gt; in your browser. You should see the message "Hello, World!" displayed.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This example shows how easy it is to create a basic server using Node.js!&lt;/p&gt;

&lt;h3&gt;
  
  
  Node.js Architecture
&lt;/h3&gt;

&lt;p&gt;Node.js has a simple but powerful architecture that helps it handle many tasks efficiently. Here's a breakdown:&lt;/p&gt;

&lt;h4&gt;
  
  
  1. &lt;strong&gt;Single-Threaded, Event-Driven Model&lt;/strong&gt;:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Single-threaded&lt;/strong&gt; means that Node.js uses just one main thread to handle all requests. &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Event-driven&lt;/strong&gt; means that it doesn’t wait for tasks like reading files or fetching data to finish. It moves on to other tasks and handles results using &lt;strong&gt;events&lt;/strong&gt; when tasks are done.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  2. &lt;strong&gt;Non-blocking I/O&lt;/strong&gt;:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Non-blocking I/O&lt;/strong&gt; means Node.js doesn't pause when waiting for tasks like file reading or database queries. Instead, it continues working on other tasks and only processes the slow ones when they're finished.&lt;/li&gt;
&lt;li&gt;This keeps the system fast and responsive, even when handling many requests at once.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  3. &lt;strong&gt;V8 JavaScript Engine&lt;/strong&gt;:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;strong&gt;V8 engine&lt;/strong&gt; is the part of Node.js that executes JavaScript code. It's built by Google and is known for being super fast. V8 converts JavaScript into machine code, allowing Node.js to run quickly and efficiently.&lt;/li&gt;
&lt;/ul&gt;




&lt;h3&gt;
  
  
  Why Use Node.js?
&lt;/h3&gt;

&lt;h4&gt;
  
  
  1. &lt;strong&gt;Speed and Performance&lt;/strong&gt;:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Node.js is fast because it uses the &lt;strong&gt;V8 engine&lt;/strong&gt; to execute JavaScript directly as machine code. Its &lt;strong&gt;non-blocking I/O&lt;/strong&gt; also helps handle many tasks at once without slowing down.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  2. &lt;strong&gt;Scalability&lt;/strong&gt;:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Node.js is great for building &lt;strong&gt;scalable applications&lt;/strong&gt;. It can handle many connections simultaneously without slowing down, making it perfect for growing apps that need to support many users or tasks.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  3. &lt;strong&gt;Full-Stack JavaScript&lt;/strong&gt;:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;With Node.js, you can use &lt;strong&gt;JavaScript&lt;/strong&gt; on both the front-end and back-end, meaning you only need to know one language for the entire project. This simplifies development and makes teams more efficient.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  4. &lt;strong&gt;NPM and its Ecosystem&lt;/strong&gt;:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Node.js comes with &lt;strong&gt;NPM&lt;/strong&gt; (Node Package Manager), which gives you access to thousands of open-source libraries and tools. This makes it easy to add features or functionality to your app without building everything from scratch.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Popular Use Cases of Node.js
&lt;/h3&gt;

&lt;h4&gt;
  
  
  1. &lt;strong&gt;Real-Time Applications&lt;/strong&gt;:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Node.js is perfect for &lt;strong&gt;real-time applications&lt;/strong&gt;, like &lt;strong&gt;chat apps&lt;/strong&gt; or &lt;strong&gt;online games&lt;/strong&gt;, where users need instant updates. It can handle many connections at the same time, without slowing down, making it ideal for apps that require quick data exchange.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  2. &lt;strong&gt;Building APIs and Microservices&lt;/strong&gt;:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Node.js is also great for creating &lt;strong&gt;APIs&lt;/strong&gt; and &lt;strong&gt;microservices&lt;/strong&gt;. It can handle many requests quickly, making it a good choice for connecting different parts of an application or for building lightweight, fast backend services.&lt;/li&gt;
&lt;/ul&gt;




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

&lt;p&gt;Node.js is fast, scalable, and efficient, making it perfect for real-time apps, APIs, and microservices. Its &lt;strong&gt;non-blocking I/O&lt;/strong&gt; and &lt;strong&gt;event-driven model&lt;/strong&gt; allow it to handle many requests simultaneously, while its use of &lt;strong&gt;JavaScript&lt;/strong&gt; on both front-end and back-end simplifies development. With a powerful &lt;strong&gt;NPM ecosystem&lt;/strong&gt;, Node.js is an excellent choice for modern, high-performance applications.&lt;/p&gt;

&lt;p&gt;Start exploring Node.js to see how it can streamline your development process!&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;Important!!&lt;br&gt;
&lt;code&gt;In my upcoming posts, I'll be diving into key topics around Node.js and JavaScript, breaking them down in a way that's simple and easy to grasp—so you can understand them with just one read! 😊 I'm always open to your questions, as I'm still learning too. Your queries help me grow and dive deeper into the topics I cover, so let's learn together. 🙌 Thanks for all your support and for enjoying the content!&lt;/code&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>javascript</category>
      <category>node</category>
      <category>npm</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Mastering JavaScript Async Patterns: From Callbacks to Async/Await</title>
      <dc:creator>Rahul Sharma</dc:creator>
      <pubDate>Fri, 13 Sep 2024 10:53:10 +0000</pubDate>
      <link>https://dev.to/okrahul/mastering-javascript-async-patterns-from-callbacks-to-asyncawait-2l18</link>
      <guid>https://dev.to/okrahul/mastering-javascript-async-patterns-from-callbacks-to-asyncawait-2l18</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;When I first encountered asynchronous JavaScript, I struggled with callbacks and had no idea how Promises worked under the hood. Over time, learning about Promises and &lt;code&gt;async&lt;/code&gt;/&lt;code&gt;await&lt;/code&gt; transformed my approach to coding, making it much more manageable. In this blog, we’ll explore these async patterns step-by-step, revealing how they can streamline your development process and make your code cleaner and more efficient. Let’s dive in and uncover these concepts together!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Why You Need to Learn Asynchronous JavaScript?
&lt;/h2&gt;

&lt;p&gt;Learning asynchronous JavaScript is essential for modern web development. It allows you to handle tasks like API requests efficiently, keeping your applications responsive and fast. Mastering async techniques, such as Promises and async/await, is crucial not only for building scalable applications but also for succeeding in JavaScript job interviews, where understanding these concepts is often a key focus. By mastering asynchronous JavaScript, you'll enhance your coding skills and better prepare yourself for real-world challenges.&lt;/p&gt;

&lt;h3&gt;
  
  
  What are Async Patterns?
&lt;/h3&gt;

&lt;p&gt;Asynchronous patterns in JavaScript are techniques used to handle tasks that take time, such as fetching data from a server, without freezing the application. Initially, developers used callbacks to manage these tasks, but this approach often led to complex and hard-to-read code, known as "callback hell." To simplify this, Promises were introduced, providing a cleaner way to handle asynchronous operations by chaining actions and handling errors more gracefully. The evolution continued with &lt;code&gt;async&lt;/code&gt;/&lt;code&gt;await&lt;/code&gt;, which allows you to write asynchronous code that looks and behaves more like synchronous code, making it easier to read and maintain. These patterns are crucial for building efficient, responsive applications and are fundamental in modern JavaScript development. We will explore these concepts in more detail throughout this blog.&lt;/p&gt;

&lt;h3&gt;
  
  
  what is callback?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Callbacks&lt;/strong&gt; are functions that you pass as arguments to other functions, with the intention that the receiving function will execute the callback at some point. This is useful for scenarios where you want to ensure some code runs after a specific task is complete, like after fetching data from a server or finishing a computation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How Callbacks Work:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;You define a function (callback).&lt;/li&gt;
&lt;li&gt;You pass this function as an argument to another function.&lt;/li&gt;
&lt;li&gt;The receiving function executes the callback at the appropriate time.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;example 1&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function fetchData(callback) {
  // Simulate fetching data with a delay
  setTimeout(() =&amp;gt; {
    const data = "Data fetched";
    callback(data); // Call the callback function with the fetched data
  }, 1000);
}

function processData(data) {
  console.log("Processing:", data);
}

fetchData(processData); // fetchData will call processData with the data

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

&lt;/div&gt;



&lt;p&gt;example 2&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Function that adds two numbers and uses a callback to return the result
function addNumbers(a, b, callback) {
  const result = a + b;
  callback(result); // Call the callback function with the result
}

// Callback function to handle the result
function displayResult(result) {
  console.log("The result is:", result);
}

// Call addNumbers with the displayResult callback
addNumbers(5, 3, displayResult);

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

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: I think callbacks are effective for handling asynchronous operations, but be cautious: as your code complexity increases, especially with nested callbacks, you may encounter a problem known as callback hell. This issue arises when callbacks are deeply nested within each other, leading to readability problems and making the code harder to maintain.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Callback Hell
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Callback Hell&lt;/strong&gt; (also known as &lt;strong&gt;Pyramid of Doom&lt;/strong&gt;) refers to the situation where you have multiple nested callbacks. This happens when you need to perform several asynchronous operations in sequence, and each operation relies on the previous one.&lt;/p&gt;

&lt;p&gt;ex. This creates a "pyramid" structure which can be hard to read and maintain.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetchData(function(data1) {
  processData1(data1, function(result1) {
    processData2(result1, function(result2) {
      processData3(result2, function(result3) {
        console.log("Final result:", result3);
      });
    });
  });
});

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Issues with Callback Hell:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Readability:&lt;/strong&gt; The code becomes difficult to read and understand.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Maintainability:&lt;/strong&gt; Making changes or debugging becomes challenging.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Error Handling:&lt;/strong&gt; Managing errors can get complicated.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Handling Errors with Callbacks
&lt;/h3&gt;

&lt;p&gt;When working with callbacks, it's common to use a pattern known as &lt;strong&gt;error-first callbacks&lt;/strong&gt;. In this pattern, the callback function takes an error as its first argument. If there is no error, the first argument is usually &lt;code&gt;null&lt;/code&gt; or &lt;code&gt;undefined&lt;/code&gt;, and the actual result is provided as the second argument.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function fetchData(callback) {
  setTimeout(() =&amp;gt; {
    const error = null; // Or `new Error("Some error occurred")` if there's an error
    const data = "Data fetched";
    callback(error, data); // Pass error and data to the callback
  }, 1000);
}

function processData(error, data) {
  if (error) {
    console.error("Error:", error);
    return;
  }
  console.log("Processing:", data);
}

fetchData(processData); // `processData` will handle both error and data

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

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: After callbacks, Promises were introduced to handle asynchronous processes in JavaScript. We will now dive deeper into Promises and explore how they work under the hood.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Introduction to Promises
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Promises&lt;/strong&gt; are objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value. They provide a cleaner way to handle asynchronous code compared to callbacks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Purpose of Promises:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Avoid Callback Hell:&lt;/strong&gt; Promises help manage multiple asynchronous operations without deep nesting.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Improve Readability:&lt;/strong&gt; Promises provide a more readable way to handle sequences of asynchronous tasks.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Promise States
&lt;/h3&gt;

&lt;p&gt;A Promise can be in one of three states:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Pending:&lt;/strong&gt; The initial state, before the promise has been resolved or rejected.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Fulfilled:&lt;/strong&gt; The state when the operation completes successfully, and &lt;code&gt;resolve&lt;/code&gt; has been called.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Rejected:&lt;/strong&gt; The state when the operation fails, and &lt;code&gt;reject&lt;/code&gt; has been called.&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: If you want to explore more, you should check out &lt;a href="https://dev.to/okrahul"&gt;Understand How Promises Work Under the Hood&lt;/a&gt; where I discuss how promises work under the hood.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;example 1&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Creating a new promise
const myPromise = new Promise((resolve, reject) =&amp;gt; {
  const success = true; // Simulate success or failure
  if (success) {
    resolve("Operation successful!"); // If successful, call resolve
  } else {
    reject("Operation failed!"); // If failed, call reject
  }
});

// Using the promise
myPromise
  .then((message) =&amp;gt; {
    console.log(message); // Handle the successful case
  })
  .catch((error) =&amp;gt; {
    console.error(error); // Handle the error case
  });

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

&lt;/div&gt;



&lt;p&gt;example 2&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const examplePromise = new Promise((resolve, reject) =&amp;gt; {
  setTimeout(() =&amp;gt; {
    const success = Math.random() &amp;gt; 0.5; // Randomly succeed or fail
    if (success) {
      resolve("Success!");
    } else {
      reject("Failure.");
    }
  }, 1000);
});

console.log("Promise state: Pending...");

// To check the state, you would use `.then()` or `.catch()`
examplePromise
  .then((message) =&amp;gt; {
    console.log("Promise state: Fulfilled");
    console.log(message);
  })
  .catch((error) =&amp;gt; {
    console.log("Promise state: Rejected");
    console.error(error);
  });

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  Chaining Promises
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Chaining&lt;/strong&gt; allows you to perform multiple asynchronous operations in sequence, with each step depending on the result of the previous one.&lt;/p&gt;

&lt;p&gt;Chaining promises is a powerful feature of JavaScript that allows you to perform a sequence of asynchronous operations where each step depends on the result of the previous one. This approach is much cleaner and more readable compared to deeply nested callbacks.&lt;/p&gt;

&lt;h3&gt;
  
  
  How Promise Chaining Works
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Promise chaining&lt;/strong&gt; involves connecting multiple promises in a sequence. Each promise in the chain executes only after the previous promise is resolved, and the result of each promise can be passed to the next step in the chain.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function step1() {
  return new Promise((resolve) =&amp;gt; {
    setTimeout(() =&amp;gt; resolve("Step 1 completed"), 1000);
  });
}

function step2(message) {
  return new Promise((resolve) =&amp;gt; {
    setTimeout(() =&amp;gt; resolve(message + " -&amp;gt; Step 2 completed"), 1000);
  });
}

function step3(message) {
  return new Promise((resolve) =&amp;gt; {
    setTimeout(() =&amp;gt; resolve(message + " -&amp;gt; Step 3 completed"), 1000);
  });
}

// Chaining the promises
step1()
  .then(result =&amp;gt; step2(result))
  .then(result =&amp;gt; step3(result))
  .then(finalResult =&amp;gt; console.log(finalResult))
  .catch(error =&amp;gt; console.error("Error:", error));

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

&lt;/div&gt;



&lt;p&gt;Disadvantages of Chaining:&lt;br&gt;
While chaining promises improves readability compared to nested callbacks, it can still become unwieldy if the chain becomes too long or complex. This can lead to readability issues similar to those seen with callback hell.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: To address these challenges, async and await were introduced to provide an even more readable and straightforward way to handle asynchronous operations in JavaScript.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;
  
  
  Introduction to Async/Await
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;async&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;await&lt;/code&gt;&lt;/strong&gt; are keywords introduced in JavaScript to make handling asynchronous code more readable and easier to work with.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;async&lt;/code&gt;&lt;/strong&gt;: Marks a function as asynchronous. An &lt;code&gt;async&lt;/code&gt; function always returns a promise, and it allows the use of &lt;code&gt;await&lt;/code&gt; within it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;await&lt;/code&gt;&lt;/strong&gt;: Pauses the execution of the &lt;code&gt;async&lt;/code&gt; function until the promise resolves, making it easier to work with asynchronous results in a synchronous-like fashion.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async function fetchData() {
  return new Promise((resolve) =&amp;gt; {
    setTimeout(() =&amp;gt; {
      resolve("Data fetched");
    }, 1000);
  });
}

async function getData() {
  const data = await fetchData(); // Wait for fetchData to resolve
  console.log(data); // Logs "Data fetched"
}

getData();

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

&lt;/div&gt;

&lt;h3&gt;
  
  
  How Async/Await Works
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;1. Async Functions Always Return a Promise:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;No matter what you return from an &lt;code&gt;async&lt;/code&gt; function, it will always be wrapped in a promise. 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;async function example() {
  return "Hello";
}

example().then(console.log); // Logs "Hello"

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

&lt;/div&gt;



&lt;p&gt;Even though &lt;code&gt;example()&lt;/code&gt; returns a string, it is automatically wrapped in a promise.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Await Pauses Execution:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;await&lt;/code&gt; keyword pauses the execution of an &lt;code&gt;async&lt;/code&gt; function until the promise it is waiting for resolves.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async function example() {
  console.log("Start");
  const result = await new Promise((resolve) =&amp;gt; {
    setTimeout(() =&amp;gt; {
      resolve("Done");
    }, 1000);
  });
  console.log(result); // Logs "Done" after 1 second
}

example();

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

&lt;/div&gt;



&lt;p&gt;In this example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;"Start"&lt;/code&gt; is logged immediately.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;await&lt;/code&gt; pauses execution until the promise resolves after 1 second.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;"Done"&lt;/code&gt; is logged after the promise resolves.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Error Handling with Async/Await
&lt;/h3&gt;

&lt;p&gt;Handling errors with &lt;code&gt;async&lt;/code&gt;/&lt;code&gt;await&lt;/code&gt; is done using &lt;code&gt;try/catch&lt;/code&gt; blocks, which makes error handling more intuitive compared to promise chains.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async function fetchData() {
  throw new Error("Something went wrong!");
}

async function getData() {
  try {
    const data = await fetchData();
    console.log(data);
  } catch (error) {
    console.error("Error:", error.message); // Logs "Error: Something went wrong!"
  }
}

getData();

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

&lt;/div&gt;



&lt;p&gt;With Promises, you handle errors using .catch():&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetchData()
  .then(data =&amp;gt; console.log(data))
  .catch(error =&amp;gt; console.error("Error:", error.message));

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

&lt;/div&gt;



&lt;p&gt;Using async/await with try/catch often results in cleaner and more readable code.&lt;/p&gt;

&lt;h3&gt;
  
  
  Combining Async/Await with Promises
&lt;/h3&gt;

&lt;p&gt;You can use &lt;code&gt;async&lt;/code&gt;/&lt;code&gt;await&lt;/code&gt; with existing promise-based functions seamlessly.&lt;/p&gt;

&lt;p&gt;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 fetchData() {
  return new Promise((resolve) =&amp;gt; {
    setTimeout(() =&amp;gt; {
      resolve("Data fetched");
    }, 1000);
  });
}

async function getData() {
  const data = await fetchData(); // Wait for the promise to resolve
  console.log(data); // Logs "Data fetched"
}

getData();

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Best Practices:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Use &lt;code&gt;async&lt;/code&gt;/&lt;code&gt;await&lt;/code&gt; for readability:&lt;/strong&gt; When dealing with multiple asynchronous operations, &lt;code&gt;async&lt;/code&gt;/&lt;code&gt;await&lt;/code&gt; can make the code more linear and easier to understand.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Combine with Promises:&lt;/strong&gt; Continue using &lt;code&gt;async&lt;/code&gt;/&lt;code&gt;await&lt;/code&gt; with promise-based functions to handle complex asynchronous flows more naturally.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Error Handling:&lt;/strong&gt; Always use &lt;code&gt;try/catch&lt;/code&gt; blocks in &lt;code&gt;async&lt;/code&gt; functions to handle potential errors.&lt;/li&gt;
&lt;/ol&gt;

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

&lt;p&gt;&lt;code&gt;async&lt;/code&gt; and &lt;code&gt;await&lt;/code&gt; provide a cleaner and more readable way to handle asynchronous operations compared to traditional promise chaining and callbacks. By allowing you to write asynchronous code that looks and behaves like synchronous code, they simplify complex logic and improve error handling with &lt;code&gt;try/catch&lt;/code&gt; blocks. Using &lt;code&gt;async&lt;/code&gt;/&lt;code&gt;await&lt;/code&gt; with promises results in more maintainable and understandable code.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>asyncprogramming</category>
      <category>promises</category>
      <category>asyncawait</category>
    </item>
    <item>
      <title>Optimizing JavaScript with Memoization: A Deep Dive into Boosting Performance:</title>
      <dc:creator>Rahul Sharma</dc:creator>
      <pubDate>Sat, 18 Nov 2023 06:43:26 +0000</pubDate>
      <link>https://dev.to/okrahul/optimizing-javascript-with-memoization-a-deep-dive-into-boosting-performance-4i4o</link>
      <guid>https://dev.to/okrahul/optimizing-javascript-with-memoization-a-deep-dive-into-boosting-performance-4i4o</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fea7pteiqhjfcem5u0z6k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fea7pteiqhjfcem5u0z6k.png" alt="banner" width="800" height="450"&gt;&lt;/a&gt;&lt;strong&gt;Introduction&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;In the fast-paced world of JavaScript, efficiency is key. One powerful technique that stands out in the pursuit of optimized code is memoization. This blog post will take you on a journey through the ins and outs of memoization, exploring its benefits and demonstrating how it can significantly enhance the performance of your JavaScript applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Memoization?&lt;/strong&gt;&lt;br&gt;
At its core, memoization is a clever optimization strategy that involves caching the results of expensive function calls based on their input parameters. This means that if a function is called with the same arguments multiple times, instead of recalculating the result, it retrieves the previously stored result. This not only speeds up your code but also reduces unnecessary computations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why Memoization Matters&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;🤙 Performance Boost: Discover how memoization can dramatically improve the speed of your code by avoiding redundant computations, making it particularly valuable for functions with heavy computational loads.&lt;/p&gt;

&lt;p&gt;🤙 Code Simplification: Learn how memoization can simplify complex logic by storing and reusing computed results. This can lead to cleaner, more readable code and reduce the need for intricate recursive structures.&lt;/p&gt;

&lt;p&gt;🤙 Versatility: Explore the versatility of memoization. From optimizing recursive functions to enhancing the efficiency of API calls, memoization can be applied in various scenarios across your codebase.&lt;/p&gt;

&lt;p&gt;Memoize function: Let's dive into the practical side of things. Explore different ways to implement memoization in JavaScript.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const memoize = () =&amp;gt; {
// Cache to store computed results
    const cache = {}

 // Returned function with memoization logic
    return (num) =&amp;gt; {

// Check if the result is already cached
        if(num in cache){
           console.log("&amp;gt;&amp;gt;&amp;gt;",{cache, num})
             return cache[num]
        }

// If not cached, perform the computation
        const res = num * 10
        cache[num] = res
        return res

     }
 }



// 🤙  Example Usage:
const memoizedFunction = memoize();

// 🤙  Call the memoized function with an argument
console.log(memoizedFunction(5)); // Output: Result retrieved from cache: { cache: { '5': 50 }, num: 5 } 50
console.log(memoizedFunction(8)); // Output: { '5': 50, '8': 80 } 80
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;It returns a new function that performs memoization. Memoization involves caching the results of expensive function calls based on their input. In this case, the function takes a single argument num and multiplies it by 10. The results are stored in the cache object to avoid redundant computations. If the result for a specific num is already in the cache, it's retrieved from there; otherwise, the computation is performed, and the result is stored in the cache for future use.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;let's see another level of memo&lt;/strong&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;here i write a memo function. It accepts a function (func) as an argument and returns a new function with memoization logic.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Memoize Function
// This higher-order function accepts a function as an argument and returns a memoized version of that function.
const memoize = (func) =&amp;gt; {
    // Cache to store computed results
    const cache = {};

    // Returned function with memoization logic
    return (...args) =&amp;gt; {
        // Convert the arguments into a string to create a unique cache key
        const key = JSON.stringify(args);

        // Check if the result is already cached
        if (key in cache) {
            console.log("&amp;gt;&amp;gt;&amp;gt; Result retrieved from cache:", { cache, args });
            return cache[key];
        }

        // If not cached, call the original function
        const result = func(...args);

        // Cache the result for future use
        cache[key] = result;

        return result;
    };
};

//  🤙  Example Usage:
//  🤙  Create a memoized version of a function
const expensiveFunction = (x, y) =&amp;gt; {
    console.log("Performing expensive computation...");
    return x * y;
};

const memoizedFunction = memoize(expensiveFunction);

//  🤙  Call the memoized function with arguments
console.log(memoizedFunction(5, 10)); // Output: Performing expensive computation... 50
console.log(memoizedFunction(5, 10)); // Output: Result retrieved from cache: { cache: { '["5","10"]': 50 }, args: [ 5, 10 ] } 50
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;let's talk about React 🚀.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;To achieve memoization in a React app with functional components, the useMemo hook proves to be a powerful tool. This hook allows you to memoize the result of a computation based on dependencies, ensuring that the computation is only recalculated when necessary.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/memoize-function-example-with-usememo-82phck"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The application includes a simple user interface with a numeric input field, allowing users to input a number. As the user types, the useMemo hook efficiently recalculates the Fibonacci result, providing real-time feedback without redundant computations. This optimization becomes particularly valuable when dealing with expensive calculations, allowing the application to respond quickly to user input while avoiding unnecessary strain on resources.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;Ready to supercharge your JavaScript efficiency? Dive into the world of memoization and elevate your coding game!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>programming</category>
      <category>react</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Unraveling Event Bubbling in JavaScript</title>
      <dc:creator>Rahul Sharma</dc:creator>
      <pubDate>Tue, 07 Nov 2023 16:37:13 +0000</pubDate>
      <link>https://dev.to/okrahul/unraveling-event-bubbling-in-javascript-2lij</link>
      <guid>https://dev.to/okrahul/unraveling-event-bubbling-in-javascript-2lij</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faywoa1fal2dm7rnuc896.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faywoa1fal2dm7rnuc896.png" alt="Img banner" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;:&lt;br&gt;
In the world of JavaScript, there are fascinating concepts that underlie the smooth interactivity of web pages. One such concept is "Event Bubbling." If you've ever wondered how events propagate through the Document Object Model (DOM) or how to harness its power for efficient event handling, you're in the right place.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Understanding Event Bubbling&lt;/strong&gt;:&lt;br&gt;
At the heart of event bubbling is the idea that when an event, such as a click, occurs on an element, it doesn't just affect that element alone. It ripples through the DOM, invoking event handlers on ancestor elements. Understanding the flow of events during bubbling is key to mastering this concept.&lt;/p&gt;

&lt;p&gt;basically, Event bubbling is the process by which an event triggered on a deeply nested element in the DOM (e.g., a button inside a div inside a section) "bubbles up" through its ancestor elements in the DOM hierarchy. It starts from the target element and travels up to the root of the document. This allows you to capture the event at different levels of the DOM, making it useful for delegation and handling events efficiently.&lt;/p&gt;

&lt;p&gt;and other hand&lt;br&gt;
Event capturing is the opposite of event bubbling. It's also known as "trickling." With event capturing, the event is captured at the top of the DOM hierarchy and then trickles down to the target element. While event capturing is less commonly used than event bubbling, it can be useful in certain scenarios, especially when you want to intercept events before they reach their target.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Order of Execution&lt;/strong&gt;:&lt;br&gt;
Event bubbling follows a predictable order, traveling from the target element up to the root of the DOM tree. We'll delve into this order of execution, helping you gain control over how your event handlers interact and respond to user actions.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm0p6y3dh7nnttx2wky26.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm0p6y3dh7nnttx2wky26.png" alt="source: Akshay Saini youtube: here he talking about event Direction of Propagation here trickling show Event capturing" width="800" height="500"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Direction of Propagation&lt;/strong&gt;:&lt;br&gt;
In event bubbling, the event propagates from the target element to its ancestor elements, starting at the target and moving up towards the root. In event capturing, the event travels in the opposite direction: from the root down to the target element.&lt;/p&gt;

&lt;p&gt;Understanding event bubbling and event capturing, along with their respective propagation directions, is essential for effective event handling in web development. Depending on your use case, you can choose the phase (bubbling or capturing) that best suits your needs to handle events and create interactive web applications.&lt;/p&gt;

&lt;p&gt;now we discus here, at third parameter in&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;document.getElementById('outer').addEventListener('click', () =&amp;gt; { console.log("hello click"); }, true);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;is a boolean value that controls the event's propagation. In this case, the value is true.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;When set to true, it specifies that the event should be captured during the capturing phase. This means that the event starts from the root of the document and propagates down to the target element. Event capturing is less commonly used than event bubbling, and it's not typically required for most use cases.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When set to false (or omitted), it indicates that the event should follow the regular event bubbling phase. This means that the event starts at the target element and bubbles up through its ancestor elements in the DOM hierarchy.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Leveraging Event Delegation&lt;/strong&gt;:&lt;br&gt;
One of the most practical applications of event bubbling is event delegation. This technique lets you manage events efficiently on a parent element, reducing the need for numerous event listeners on individual elements. We'll explore how event delegation simplifies event handling and enhances performance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Custom Event Systems&lt;/strong&gt;:&lt;br&gt;
In the realm of advanced web development, you might find the need to create your custom event systems. Understanding event bubbling is crucial for implementing your own event-driven architecture, providing the flexibility to build robust applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Delegated event handling&lt;/strong&gt;:&lt;br&gt;
Delegated event handling is a technique where you attach a single event listener to a common ancestor element of multiple child elements. This listener then handles events for all the child elements. It's an efficient way to manage events on dynamically generated or numerous child elements. Here's a simple example using JavaScript and HTML:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;body&amp;gt;
  &amp;lt;ul id="myList"&amp;gt;
    &amp;lt;li&amp;gt;Item 1&amp;lt;/li&amp;gt;
    &amp;lt;li&amp;gt;Item 2&amp;lt;/li&amp;gt;
    &amp;lt;li&amp;gt;Item 3&amp;lt;/li&amp;gt;
    &amp;lt;li&amp;gt;Item 4&amp;lt;/li&amp;gt;
  &amp;lt;/ul&amp;gt;

  &amp;lt;script&amp;gt;
    // Add a single click event listener to the common parent element (ul)
    document.getElementById('myList').addEventListener('click', function (event) {
      // Check if the clicked element is an li
      if (event.target.tagName === 'LI') {
        // Handle the event for li elements
        alert(`You clicked on ${event.target.innerText}`);
      }
    });
  &amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;"Explore and Learn: Code Example for Practicing Different Scenarios"&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;title&amp;gt;Event Bubbling Example&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;div id="outer" style="border: 1px solid red;"&amp;gt;
    &amp;lt;p&amp;gt;Click me!&amp;lt;/p&amp;gt;
  &amp;lt;/div&amp;gt;
  &amp;lt;div id="inner" style="border: 1px solid blue;"&amp;gt;
    &amp;lt;p&amp;gt;Click me too!&amp;lt;/p&amp;gt;
  &amp;lt;/div&amp;gt;

  &amp;lt;script&amp;gt;
    // Event handler function
    function handleClick(event) {
      const element = event.target;
      console.log(`Clicked on ${element.tagName}`);
    }

    // Add click event listeners
    document.getElementById('outer').addEventListener('click', handleClick);
    document.getElementById('inner').addEventListener('click', handleClick);
  &amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;


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

&lt;/div&gt;



</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>react</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Weather app</title>
      <dc:creator>Rahul Sharma</dc:creator>
      <pubDate>Wed, 19 Jan 2022 18:40:28 +0000</pubDate>
      <link>https://dev.to/okrahul/weather-app-1aa5</link>
      <guid>https://dev.to/okrahul/weather-app-1aa5</guid>
      <description>&lt;p&gt;The Weather App In Javascript is a fun project that focuses on simple weather forecasting. The user can examine the current state of the climate probability and forecast whether the day will be sunny or cloudy. In the software, the user can write down the name of any city in the world. This Javascript Project With Source Code was created with JavaScript, CSS, and HTML.&lt;/p&gt;

&lt;p&gt;👉 Live Demo🔴:- shorturl.at/juHX8&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>html</category>
      <category>css</category>
    </item>
    <item>
      <title>Windows Calculator</title>
      <dc:creator>Rahul Sharma</dc:creator>
      <pubDate>Sun, 12 Dec 2021 07:14:32 +0000</pubDate>
      <link>https://dev.to/okrahul/windows-calculator-51mi</link>
      <guid>https://dev.to/okrahul/windows-calculator-51mi</guid>
      <description>&lt;h5&gt;This calculator looking and functions like windows 10 calculator.&lt;/h5&gt;

&lt;p&gt;Looking and function like windows 10 💻 calculate. &lt;br&gt;&lt;br&gt;
&lt;a href="https://ibb.co/SJ8kYMk" rel="noopener noreferrer"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Live Demo &lt;a href="https://windowscalculator.netlify.app/" rel="noopener noreferrer"&gt; #WindowsCalculator &lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;h3&gt;Technologies used:&lt;/h3&gt;
&lt;li&gt;HTML(Structure Building)&lt;/li&gt;
&lt;li&gt;CSS(Designing/Presentation)&lt;/li&gt;
&lt;li&gt;JavaScript(Logic Implemetation)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;Let's Design Calulator Using HTML and CSS&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;HTML(hypertext Markup Language) is the standard markup language used to create basic structure of the website.&lt;/li&gt;
&lt;li&gt;CSS (Cascading Style Sheets) describes how HTML elements are to be displayed on screen. It can control the layout of multiple web pages all at once.&lt;/li&gt;

&lt;li&gt; JavaScript - We can do this by putting some classes in the HTML file. However, since we do not want to mix CSS classes with JavaScript classes, we can use data attributes to select them instead.

data-operation to represent your operation buttons, data-numbers to represent the number buttons, data-all-clear to represent the All-Clear button and data-delete to represent the Delete button. We can add these classes to the previous-operand and current-operand&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;&lt;iframe height="600" src="https://codepen.io/okrahul/embed/jOGWyKz?height=600&amp;amp;default-tab=result&amp;amp;embed-version=2"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

</description>
      <category>html</category>
      <category>css</category>
      <category>javascript</category>
      <category>codepen</category>
    </item>
  </channel>
</rss>
