<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Siddhesh.Shende Blog's]]></title><description><![CDATA[Made by the INTERNET, For the INTERNET.]]></description><link>https://blog.siddheshshende.com</link><generator>RSS for Node</generator><lastBuildDate>Sat, 18 Apr 2026 11:45:30 GMT</lastBuildDate><atom:link href="https://blog.siddheshshende.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Top Ways to Use "this" Keyword in JavaScript.]]></title><description><![CDATA[Introduction
JavaScript is a strong and flexible programming language, yet its peculiar ideas and actions sometimes confuse engineers. The "this" keyword stands out among them as one of the trickiest yet most important to learn. The object that "this...]]></description><link>https://blog.siddheshshende.com/top-ways-to-use-this-keyword-in-javascript</link><guid isPermaLink="true">https://blog.siddheshshende.com/top-ways-to-use-this-keyword-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[WeMakeDevs]]></category><dc:creator><![CDATA[Siddhesh Shende]]></dc:creator><pubDate>Mon, 17 Jun 2024 13:43:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1718631473658/c6dbb7f3-6c4e-4215-9042-bbf075870250.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>JavaScript is a strong and flexible programming language, yet its peculiar ideas and actions sometimes confuse engineers. The <mark>"this" keyword</mark> stands out among them as one of the trickiest yet most important to learn. The object that "this" in JavaScript refers to can vary significantly depending on the context in which it is used. We shall examine every scenario in which "this" is used in this post and try to solve the enigma surrounding its behaviour.</p>
<hr />
<h2 id="heading-1-this-in-the-global-contextspace">1. "this" in the global context(space)</h2>
<p>The global object is referred to when the "this" keyword is used in the global space.</p>
<p>global object is different in different javascript runtime environment like js is differrent on smart bulbs,smart watches, node.js, browser etc. It depends on where you run the js code.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>); <span class="hljs-comment">// refers to global object i.e. window in a browser or global in node.js</span>
</code></pre>
<h2 id="heading-2this-inside-a-function">2."this" inside a function</h2>
<p>The behavior of "this" inside a function varies based on strict mode and non-strict mode(i.e it works differently in both mode).</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">x</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
    <span class="hljs-comment">// In strict mode:o/p is undefined</span>
    <span class="hljs-comment">// In non-strict mode:o/p is global object</span>
}
x();
</code></pre>
<p>When "use strict" is used at the beginning of the script, "this" acts differently inside functions. "this" inside a function is undefined in strict mode, but it points to the global object in non-strict mode.  </p>
<h2 id="heading-3this-substitution">3."this" Substitution</h2>
<p>In non-strict mode, the global object is used(replaced) in place of "this" if the value is null or undefined.</p>
<p><code>this</code> keyword value depends on how the <code>function</code> is called.</p>
<pre><code class="lang-javascript"><span class="hljs-meta">"use strict"</span>;
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">x</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
    }
x();
<span class="hljs-comment">// o/p: window(object)</span>
<span class="hljs-comment">//      undefined </span>

<span class="hljs-comment">//without using strict-mode</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">x</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
    }
x();
<span class="hljs-comment">// o/p: window(object)</span>
<span class="hljs-comment">//     window(object)  </span>
<span class="hljs-comment">//in non strict mode, "this substitution" takes place and "this" points to globalObject</span>
</code></pre>
<h2 id="heading-4this-in-the-method-of-an-object">4."this" in the Method of an Object:</h2>
<p>"This" refers to the object itself in the context of its method.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> obj = {
    <span class="hljs-attr">a</span>: <span class="hljs-number">10</span>,
    <span class="hljs-attr">x</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>); <span class="hljs-comment">// o/p: {a: 10, x: f()}</span>
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.a); <span class="hljs-comment">// o/p: 10</span>
    }
}
obj.x();
</code></pre>
<p><strong>Difference between function and method:</strong></p>
<p>When you make a function as a part of of object , then it is know as method.</p>
<p>when you create a function inside an object, then function x will be a method. So, "x" is a method of object "obj".</p>
<h2 id="heading-5call-apply-amp-bind-methods">5.call, apply &amp; bind Methods</h2>
<p>The value of "this" can be explicitly set via the call, apply, and bind methods. Basically, they are used to control the value of "this" inside a function.</p>
<p>call, apply &amp; bind are used to share a method with another object (hence,the "this" keyword reference would also change accordingly).</p>
<p><code>call</code> and <code>apply</code>Both methods immediately invoke the function.But, bind method does not invoke immediately.</p>
<p>call () takes arguments separately (fixed number of arguments.),whereas apply() takes arguments as an array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> student = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'siddhesh'</span>,
    <span class="hljs-attr">printName</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name);
    }
}
student.printName(); <span class="hljs-comment">// o/p: siddhesh</span>

<span class="hljs-keyword">const</span> student2 = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Karan'</span>,
}
student.printName.call(student2); 
<span class="hljs-comment">// o/p: Karan</span>
<span class="hljs-comment">//In this case, the call method modifies "this" to refer to student2.</span>
</code></pre>
<h2 id="heading-6this-inside-arrow-function">6."this" inside arrow function</h2>
<p>Arrow functions do not have their own "this" context. Instead, they inherit "this" from the enclosing lexical context. (lexical context: it depends on where it is present).</p>
<p>In short, they take the value of their lexical context which is enclosed.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> student ={
    <span class="hljs-attr">name</span>: <span class="hljs-string">"siddhesh"</span>,
    <span class="hljs-attr">printname</span>:  <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
    }
}
student.printname();
<span class="hljs-comment">//o/p: { name: 'siddhesh', printname: [Function: printname] }</span>
 <span class="hljs-comment">//now, using arrow function</span>
<span class="hljs-keyword">const</span> student ={
    <span class="hljs-attr">name</span>: <span class="hljs-string">"siddhesh"</span>,
    <span class="hljs-attr">printname</span>:<span class="hljs-function">()=&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
    }
}
student.printname();
<span class="hljs-comment">//o/p: window(object) as it is lexical scope of "this".</span>
<span class="hljs-comment">//but, actually is is not present/written in global space. "this" in arrow function behaves differently than regular functions.</span>
</code></pre>
<h2 id="heading-7this-inside-the-dom">7."this" Inside the DOM</h2>
<p>"this" in DOM refers to the HTML element itself on which it is being used.</p>
<pre><code class="lang-javascript">&lt;button onclick=<span class="hljs-string">"alert(this)"</span>&gt;Click Me&lt;/button&gt;
<span class="hljs-comment">//o/p: &lt;!-- [object HTMLButtonElement] Button element --&gt;</span>
<span class="hljs-comment">//here, "this" will be referred to buttons.</span>
<span class="hljs-comment">//another example:</span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"alert(this.tagName)"</span>&gt;</span>Click Me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
<span class="hljs-comment">//o/p: alert box will be displayed with "Buttton" tag.</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion:</h2>
<p>JavaScript's "this" keyword behaves differently depending on the context. Writing efficient JavaScript code requires an understanding of how "this" changes depending on where and how it is used. Whether you use "this" in global space, inside functions, methods or arrow functions etc which will improve your JavaScript significantly.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1718631137782/3cf1c9c7-c71f-4411-8e1e-03cad3192e13.jpeg" alt class="image--center mx-auto" /></p>
<hr />
]]></content:encoded></item><item><title><![CDATA[Asynchronous JavaScript with Promise APIs (all, allSettled, race and any)]]></title><description><![CDATA[Introduction
JavaScript asynchronous programming is an essential ability for recent developers. Promises have made it easier to handle asynchronous tasks and reduced the likelihood of errors. With promises, handling callbacks is simplified, improving...]]></description><link>https://blog.siddheshshende.com/asynchronous-javascript-with-promise-apis-all-allsettled-race-and-any</link><guid isPermaLink="true">https://blog.siddheshshende.com/asynchronous-javascript-with-promise-apis-all-allsettled-race-and-any</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[WeMakeDevs]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Siddhesh Shende]]></dc:creator><pubDate>Sat, 18 May 2024 21:35:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1716067869390/c610c377-543d-4b20-846e-765fd6b7d24f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>JavaScript asynchronous programming is an essential ability for recent developers. Promises have made it easier to handle asynchronous tasks and reduced the likelihood of errors. With promises, handling callbacks is simplified, improving the readability and maintainability of your code. Four significant <mark> Promise API's</mark> are <code>Promise.all, Promise.allSettled , Promise.race and Promise.any</code> will be discussed in this article.This promise API's are used basically to make multiple API calls in parallel way. Gaining a knowledge of them will provide you the ability to manage several asynchronous jobs successfully and efficiently.</p>
<hr />
<h2 id="heading-1promiseall">1.Promise.all()</h2>
<p>Promise.all() provides a single promise after accepting an array or iterable of promises. When every promise in the array resolves, this one resolves as well; if any of the promises reject, it rejects.</p>
<p>consider,there are multiple API calls or promises to be fetched. So, it will handle multiple promises together.It will wait for all of them(API calls) to finish and result is displayed at same time in console in resolve case.</p>
<p>But, in reject case, if any one of the promise is reject, then promise.all() will throw an error and it will not wait for other promise results (that can be success or failure).  </p>
<p><strong>Use Case:</strong></p>
<p>Promise.all is used when you need to make multiple API calls at once and wait for each one to finish. For example, retrieving information concurrently from several sources.</p>
<p>Promise.all([p1, p2, p3]) -&gt; Lets assume we are making 3 API call to fetch data. Also assume p1 takes 3 seconds, p2 takes 1 second, p3 takes 2 seconds.</p>
<p>In first scenario let's assume all 3 promises are successful. So Promise.all will take 3secs and will give promise value of result like [val1, val2, val3]. It will wait for all of them to finish then it will collect the results and give array as output.</p>
<p>What if any of the promise gets rejected, for eg: Promise.all([p1, p2, p3]). But this time, p2 get rejected after 1 sec. Thus Promise.all will throw same error as p2 immediately as soon as error happened. It will not wait for other promise to either become success or failure.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// First case</span>

<span class="hljs-keyword">const</span> p1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'P1 Success'</span>);
  }, <span class="hljs-number">3000</span>);
});
<span class="hljs-keyword">const</span> p2 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'P2 Success'</span>);
  }, <span class="hljs-number">1000</span>);
});
<span class="hljs-keyword">const</span> p3 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'P3 Success'</span>);
  }, <span class="hljs-number">2000</span>);
});

<span class="hljs-built_in">Promise</span>.all([p1, p2, p3]).then(<span class="hljs-function">(<span class="hljs-params">results</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(results); 
});
<span class="hljs-comment">// o/p: ['P1 Success', 'P2 Success', 'P3 Success'] -&gt; took 3 secs</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1716063420275/38cc7ac4-d598-4298-9db8-537f1723db24.jpeg" alt class="image--center mx-auto" /></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Second case</span>
<span class="hljs-keyword">const</span> p1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'P1 Success'</span>);
  }, <span class="hljs-number">3000</span>);
});
<span class="hljs-keyword">const</span> p2 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    reject(<span class="hljs-string">'P2 Fail'</span>);
  }, <span class="hljs-number">1000</span>);
});
<span class="hljs-keyword">const</span> p3 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'P3 Success'</span>);
  }, <span class="hljs-number">2000</span>);
});

<span class="hljs-built_in">Promise</span>.all([p1, p2, p3])
  .then(<span class="hljs-function"><span class="hljs-params">results</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(results))
  .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(err)); 
<span class="hljs-comment">//o/p: throws error after 1 sec i.e. 'P2 Fails'</span>
</code></pre>
<p>But, Its ok if one of our promise fails.I want other 9 out of 10 promises to be displayed. In this situation, promise.all() will not work. So, promise.allsettled() is introduced.</p>
<h2 id="heading-2promiseallsettled">2.Promise.AllSettled()</h2>
<p>Once all of the input promises have settled, either resolved or refused, Promise.allSettled() gives a promise that resolves. It offers a thorough analysis of every promise's performance.</p>
<p>If one of our promise is failed, then Promise.AllSettled() will wait for all other promises to settled.This Promises API is the safest of all.</p>
<blockquote>
<p>Promise.all() -&gt; Very Quick Failure(fail fast)<br />Promise.AllSettled() -&gt; Promise Will await and deliver final outcomes</p>
</blockquote>
<p><strong>Use Case:</strong></p>
<p>when you have to wait for every promise—regardless of whether it was accepted or rejected—to be fulfilled.</p>
<p>Promise.allSettled([p1, p2, p3]) -&gt; Lets assume we are making 3 API call to fetch data. Also assume <strong>p1</strong> takes <strong>3 seconds</strong>, <strong>p2</strong> takes <strong>1 second</strong>, <strong>p3</strong> takes <strong>2 seconds</strong>.</p>
<p>In first scenario let's assume all 3 promises are successful. So Promise.allSettled will take <strong>3secs</strong> and will give promise value of result like [val1, val2, val3]. It will wait for all of them to finish then it will collect the results and give array as output.</p>
<p>What if any of the promise gets rejected, for eg: Promise.all([p1, p2, p3]). But this time, p2 get rejected after 1 sec. Thus Promise.allSettled will still wait for all promises to get settled. So After 3 secs, it will be [val1, err, val3]</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> p1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'P1 Success'</span>);
  }, <span class="hljs-number">3000</span>);
});
<span class="hljs-keyword">const</span> p2 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'P2 Success'</span>);
  }, <span class="hljs-number">1000</span>);
});
<span class="hljs-keyword">const</span> p3 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    reject(<span class="hljs-string">'P3 Fail'</span>);
  }, <span class="hljs-number">2000</span>);
});

<span class="hljs-built_in">Promise</span>.allSettled([p1, p2, p3])
  .then(<span class="hljs-function">(<span class="hljs-params">results</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(results))
  .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(err));<span class="hljs-comment">//we can also do (err.errors) for detailed output.</span>

<span class="hljs-comment">// Over here, it will wait for all promises to be either settled or rejected and then return,</span>
  <span class="hljs-comment">/*
    [
      {status: 'fulfilled', value: 'P1 Success'},
      {status: 'fulfilled', value: 'P2 Success'},
      {status: 'rejected', reason: 'P3 Fail'}
    ]
  */</span>
</code></pre>
<h2 id="heading-3promiserace">3.Promise.race()</h2>
<p>As soon as one of the input promises resolves or rejects, Promise.race() returns a promise that does the same. It truly is a race between the promises.It will not wait for other promises to finish because its a race.</p>
<p>It basically give us value of first settled promise.And if the first promise which should be settled is rejected ,then it will throw an error.  </p>
<p><strong>Use Case:</strong>  </p>
<p>When you require the fastest promise's result, no matter how quickly it happens.</p>
<p>Promise.race([p1, p2, p3]) -&gt; Lets assume we are making 3 API call to fetch data. Also assume <strong>p1</strong> takes <strong>3 seconds</strong>, <strong>p2</strong> takes <strong>1 second</strong>, <strong>p3</strong> takes <strong>2 seconds</strong>. So as soon as first promise will resolve or reject, it will give the output.</p>
<p>So in Happy scenario, Promise.race will give (val2) as output after 1sec as p2 got resolved at the earliest. Whereas if it would have been failed Promise.race would have still given output after 1 sec but this time with error.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//First case</span>
<span class="hljs-keyword">const</span> p1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'P1 Success'</span>);
  }, <span class="hljs-number">3000</span>);
});
<span class="hljs-keyword">const</span> p2 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'P2 Success'</span>);
  }, <span class="hljs-number">1000</span>);
});
<span class="hljs-keyword">const</span> p3 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    reject(<span class="hljs-string">'P3 Fail'</span>);
  }, <span class="hljs-number">2000</span>);
});

<span class="hljs-built_in">Promise</span>.race([p1, p2, p3])
  .then(<span class="hljs-function">(<span class="hljs-params">results</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(results))
  .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(err));

 <span class="hljs-comment">// It will return as soon as first promise is resolved or rejected.</span>
 <span class="hljs-comment">// O/P: "P2 Success"</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">//Second case</span>
<span class="hljs-keyword">const</span> p1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'P1 Success'</span>);
  }, <span class="hljs-number">3000</span>);
});
<span class="hljs-keyword">const</span> p2 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'P2 Success'</span>);
  }, <span class="hljs-number">5000</span>);
});
<span class="hljs-keyword">const</span> p3 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    reject(<span class="hljs-string">'P3 Fail'</span>);
  }, <span class="hljs-number">2000</span>);
});

<span class="hljs-built_in">Promise</span>.race([p1, p2, p3])
  .then(<span class="hljs-function">(<span class="hljs-params">results</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(results))
  .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(err));

 <span class="hljs-comment">//After 2 secs O/P: "P3 Fail"</span>
</code></pre>
<blockquote>
<p>Insights:<br />As soon as a promise is fulfilled, the outcome is obtained.</p>
<p>Furthermore, settled can be broadly classified into two categories:</p>
<p>1.reject, failure, rejected</p>
<p>2.resolve, success, fulfilled</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1716065747003/32015554-7ffb-4cc4-8430-efddfcad8198.jpeg" alt class="image--center mx-auto" /></p>
</blockquote>
<h2 id="heading-4promiseany">4.Promise.any()</h2>
<p>A promise that resolves as soon as any of the input promises resolves is returned by Promise.any(). An aggregated error is nothing but array of all error like [err1, err2, err3] is returned if every promise/API call is rejected/failed.</p>
<p>It is similar to promise.race(). But, it will wait for first success/resolved /fulfilled promise. It is a <strong>success seeking</strong> promise means it will return result only after/whenever it is successful.</p>
<p><strong>Use case:</strong>  </p>
<p>when you require the first of multiple promises to be fulfilled successfully.</p>
<p>Promise.any([p1, p2, p3]) -&gt; Lets assume we are making 3 API call to fetch data. Also assume <strong>p1</strong> takes <strong>3 seconds</strong>, <strong>p2</strong> takes <strong>1 second</strong>, <strong>p3</strong> takes <strong>2 seconds</strong>. So as soon as first promise will be successful, it will give the output.</p>
<p>If in above situation what if p2 got rejected, nothing will happen as Promise.any seek for success, so the moment first success will happen that will become the result.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// First case</span>
<span class="hljs-keyword">const</span> p1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'P1 Success'</span>);
  }, <span class="hljs-number">3000</span>);
});
<span class="hljs-keyword">const</span> p2 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'P2 Success'</span>);
  }, <span class="hljs-number">5000</span>);
});
<span class="hljs-keyword">const</span> p3 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    reject(<span class="hljs-string">'P3 Fail'</span>);
  }, <span class="hljs-number">2000</span>);
});

<span class="hljs-built_in">Promise</span>.any([p1, p2, p3])
  .then(<span class="hljs-function">(<span class="hljs-params">results</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(results))
  .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(err));

<span class="hljs-comment">// It will wait for first settled **success**</span>
<span class="hljs-comment">// In above, p3 will settled first, but since it is rejected, </span>
<span class="hljs-comment">//so it will wait further and at 3rd second it will print "P1 Success"</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">// second case</span>
<span class="hljs-keyword">const</span> p1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    reject(<span class="hljs-string">'P1 Fail'</span>);
  }, <span class="hljs-number">3000</span>);
});
<span class="hljs-keyword">const</span> p2 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'P2 Success'</span>);
  }, <span class="hljs-number">5000</span>);
});
<span class="hljs-keyword">const</span> p3 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    reject(<span class="hljs-string">'P3 Fail'</span>);
  }, <span class="hljs-number">2000</span>);
});

<span class="hljs-built_in">Promise</span>.any([p1, p2, p3])
  .then(<span class="hljs-function">(<span class="hljs-params">results</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(results))
  .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(err));

<span class="hljs-comment">// o/p: After 5 secs: 'P2 Success'</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">//Third case</span>
<span class="hljs-keyword">const</span> p1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    reject(<span class="hljs-string">'P1 Fail'</span>);
  }, <span class="hljs-number">3000</span>);
});
<span class="hljs-keyword">const</span> p2 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    reject(<span class="hljs-string">'P2 Fail'</span>);
  }, <span class="hljs-number">5000</span>);
});
<span class="hljs-keyword">const</span> p3 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    reject(<span class="hljs-string">'P3 Fail'</span>);
  }, <span class="hljs-number">2000</span>);
});

<span class="hljs-built_in">Promise</span>.any([p1, p2, p3])
  .then(<span class="hljs-function">(<span class="hljs-params">results</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(results))
  .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.error(err);
    <span class="hljs-built_in">console</span>.error(err.errors); 
  });
<span class="hljs-comment">// o/p: ['P1 Fail', 'P2 Fail', 'P3 Fail']</span>
<span class="hljs-comment">// Since all are rejected, so it will give "aggregate error" as output</span>
<span class="hljs-comment">// AggregateError: All promises were rejected</span>
<span class="hljs-comment">// To get AggregateError array you need to write "err.errors"</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion:</h2>
<p>Gain more proficiency managing asynchronous processes in JavaScript by learning and utilising these Promise APIs: Promise.all, Promise.allSettled, Promise.race and Promise.any. Every API has a distinct function, such as Promise.all to concurrently process multiple promises, Promise.allSettled to handle all promise states, Promise.race for executing the fastest promise, and Promise.any for managing the first resolved promise.Making use of these will greatly enhance your asynchronous programming abilities.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1716067238305/97606e7b-a078-4f10-af92-8c77efa4436f.jpeg" alt class="image--center mx-auto" /></p>
<hr />
]]></content:encoded></item><item><title><![CDATA[Async/Await in Modern JavaScript Development.]]></title><description><![CDATA[Introduction
Learning asynchronous programming is super important in the fast-paced world of JavaScript development today. Understanding the magic of async and await  can make developers write code that's not just elegant but also super productive. J...]]></description><link>https://blog.siddheshshende.com/asyncawait-in-modern-javascript-development</link><guid isPermaLink="true">https://blog.siddheshshende.com/asyncawait-in-modern-javascript-development</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[WeMakeDevs]]></category><dc:creator><![CDATA[Siddhesh Shende]]></dc:creator><pubDate>Mon, 22 Apr 2024 16:37:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1713803491929/a13e9b04-41b6-4b3d-93d6-c11dbcc1f6b8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Learning asynchronous programming is super important in the fast-paced world of JavaScript development today. Understanding the magic of <mark>async and await </mark> can make developers write code that's not just elegant but also super productive. Join us on a journey to explore these cool concepts and see how they've totally changed the game in JavaScript development today.</p>
<h2 id="heading-async-what-is-it">Async: What Is It?</h2>
<p>Fundamentally, async is a keyword that comes before a function and makes it an async function. This little change gives the function the ability to run asynchronously, which enables non-blocking JavaScript activities. It always return a promise.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//  async function always returns a promise, </span>
<span class="hljs-comment">//even if I return a simple string,boolean or number etc from below function, async keyword will wrap it under Promise and then return.</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">"Namaste JavaScript"</span>;
}
<span class="hljs-keyword">const</span> dataPromise = getData();
<span class="hljs-built_in">console</span>.log(dataPromise); <span class="hljs-comment">// Promise {&lt;fulfilled&gt;: 'Namaste JavaScript'}</span>

<span class="hljs-comment">//How to extract data from above promise?? One way is using promise .then</span>
dataPromise.then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(res)); <span class="hljs-comment">// Namaste JavaScript</span>

<span class="hljs-comment">//One more instance of an async function returning a promise: </span>
<span class="hljs-keyword">const</span> p = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  resolve(<span class="hljs-string">'Promise resolved value!!'</span>);
})

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> p;
}
<span class="hljs-comment">// In above case, since we are already returning a promise async function would simply return that instead of wrapping with a new Promise.</span>
<span class="hljs-keyword">const</span> dataPromise = getData();
<span class="hljs-built_in">console</span>.log(dataPromise); <span class="hljs-comment">// Promise {&lt;fulfilled&gt;: 'Promise resolved value!!'}</span>
dataPromise.then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(res)); <span class="hljs-comment">// Promise resolved value!!</span>
</code></pre>
<h2 id="heading-whats-await">What's Await?</h2>
<p>As an addition to async, await is a keyword that works inside async functions to make handling promises easier. Through the usage of await, developers can halt code execution until a promise is fulfilled, making asynchronous programming easier to understand and more linear.</p>
<h3 id="heading-how-we-can-use-await-along-with-async-function">How we can use <code>await</code> along with async function?</h3>
<p><code>async</code> and <code>await</code> combo is used to handle promises. <code>await</code> is a keyword that can only be used inside a <code>async</code> function, otherwise it will throw syntax error.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//old method:</span>
<span class="hljs-keyword">const</span> p = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  resolve(<span class="hljs-string">'Promise resolved value!!'</span>);
})

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
  p.then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(res));
}
getData(); <span class="hljs-comment">// Promise resolved value!!</span>

<span class="hljs-comment">//Till now, we have been using Promise.then/.catch to handle promise.</span>
<span class="hljs-comment">//Now let's see, how async await can help us and how it is different</span>
<span class="hljs-comment">//New method:</span>
<span class="hljs-comment">// The rule is we have to use keyword await in front of promise.</span>
<span class="hljs-keyword">const</span> p = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  resolve(<span class="hljs-string">'Promise resolved value!!'</span>);
})
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handlePromise</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> val = <span class="hljs-keyword">await</span> p;
  <span class="hljs-built_in">console</span>.log(val);
}
handlePromise(); <span class="hljs-comment">// Promise resolved value!!</span>
</code></pre>
<h3 id="heading-why-is-async-await-unique">Why is async-await unique?</h3>
<p>To better understand, let's compare the async-await method of promise resolution with an earlier one using an example.then/catch the trend. To accomplish this, we will modify the promise we made.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> p = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'Promise resolved value!!'</span>);
  }, <span class="hljs-number">3000</span>);
})

<span class="hljs-comment">// Let's now compare with some modification:</span>

<span class="hljs-comment">//Promise.then/.catch way:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// JS engine will not wait for promise to be resolved</span>
  p.then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(res));
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello There!'</span>);
}

getData(); <span class="hljs-comment">// First `Hello There!` would be printed and then after 3 secs 'Promise resolved value!!' will be printed.</span>
<span class="hljs-comment">// Above happened as Javascript wait for none, so it will register this promise and take this callback function and register separately then js will move on and execute the following console and later once promise is resolved, following console will be printed.</span>

<span class="hljs-comment">//Problem: Normally one used to get confused that JS will wait for promise to be resolved before executing following lines.</span>

<span class="hljs-comment">//async-wait way:</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handlePromise</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// JS Engine will waiting for promise to resolve.</span>
  <span class="hljs-keyword">const</span> val = <span class="hljs-keyword">await</span> p;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello There!'</span>);
  <span class="hljs-built_in">console</span>.log(val);
}
handlePromise(); <span class="hljs-comment">// This time `Hello There!` won't be printed immediately instead after 3 secs `Hello There!` will be printed followed by 'Promise resolved value!!'</span>
<span class="hljs-comment">//  So basically code was waiting at `await` line to get the promise resolve before moving on to next line.</span>

<span class="hljs-comment">// Above is the major difference between Promise.then/.catch vs async-await</span>

<span class="hljs-comment">// Let's brainstorm more around async-await</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handlePromise</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hi'</span>);
  <span class="hljs-keyword">const</span> val = <span class="hljs-keyword">await</span> p;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello There!'</span>);
  <span class="hljs-built_in">console</span>.log(val);

  <span class="hljs-keyword">const</span> val2 = <span class="hljs-keyword">await</span> p;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello There! 2'</span>);
  <span class="hljs-built_in">console</span>.log(val2);
}
handlePromise(); 
<span class="hljs-comment">// In above code example, will our program wait for 2 time or will it execute parallely.</span>
<span class="hljs-comment">//`Hi` printed instantly -&gt; now code will wait for 3 secs -&gt; After 3 secs both promises will be resolved so ('Hello There!' 'Promise resolved value!!' 'Hello There! 2' 'Promise resolved value!!') </span>
<span class="hljs-comment">//will get printed immediately.</span>

<span class="hljs-comment">// Let's create one promise and then resolve two different promise.</span>
<span class="hljs-keyword">const</span> p2 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'Promise resolved value by p2!!'</span>);
  }, <span class="hljs-number">2000</span>);
})

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handlePromise</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hi'</span>);
  <span class="hljs-keyword">const</span> val = <span class="hljs-keyword">await</span> p;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello There!'</span>);
  <span class="hljs-built_in">console</span>.log(val);

  <span class="hljs-keyword">const</span> val2 = <span class="hljs-keyword">await</span> p2;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello There! 2'</span>);
  <span class="hljs-built_in">console</span>.log(val2);
}
handlePromise(); 
<span class="hljs-comment">//`Hi` printed instantly -&gt; now code will wait for 3 secs -&gt; After 3 secs both promises will be resolved so ('Hello There!' 'Promise resolved value!!' 'Hello There! 2' 'Promise resolved value by p2!!') </span>
<span class="hljs-comment">//will get printed immediately. So even though `p2` was resolved after 2 secs it had to wait for `p` to get resolved</span>


<span class="hljs-comment">// Now let's reverse the order execution of promise and observe response.</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handlePromise</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hi'</span>);
  <span class="hljs-keyword">const</span> val = <span class="hljs-keyword">await</span> p2;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello There!'</span>);
  <span class="hljs-built_in">console</span>.log(val);

  <span class="hljs-keyword">const</span> val2 = <span class="hljs-keyword">await</span> p;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello There! 2'</span>);
  <span class="hljs-built_in">console</span>.log(val2);
}
handlePromise(); 
<span class="hljs-comment">// `Hi` printed instantly -&gt; now code will wait for 2 secs -&gt; After 2 secs ('Hello There!' 'Promise resolved value by p2!!') </span>
<span class="hljs-comment">//will get printed and in the subsequent second i.e. after 3 secs ('Hello There! 2' 'Promise resolved value!!') will get printed</span>
</code></pre>
<h3 id="heading-is-the-program-genuinely-waiting-or-is-something-else-going-on-in-the-background">Is the program genuinely waiting or is something else going on in the background?</h3>
<p>Time, tide, and JS, as we all know, wait for no one. That is accurate. Although it looks like the JS engine is waiting over here, it is not. It hasn't taken up any space in the call stack; if it had, our page might have frozen. Thus, the JS engine is not idle. What is it doing in the background if it isn't waiting? Let's explore with the code sample below.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> p1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'Promise resolved value by p1!!'</span>);
  }, <span class="hljs-number">5000</span>);
})

<span class="hljs-keyword">const</span> p2 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'Promise resolved value by p2!!'</span>);
  }, <span class="hljs-number">10000</span>);
})

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handlePromise</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hi'</span>);
  <span class="hljs-keyword">debugger</span>;
  <span class="hljs-keyword">const</span> val = <span class="hljs-keyword">await</span> p;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello There!'</span>);
  <span class="hljs-keyword">debugger</span>;
  <span class="hljs-built_in">console</span>.log(val);

  <span class="hljs-keyword">const</span> val2 = <span class="hljs-keyword">await</span> p2;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello There! 2'</span>);
  <span class="hljs-keyword">debugger</span>;
  <span class="hljs-built_in">console</span>.log(val2);
}
handlePromise(); 
<span class="hljs-comment">// When this function is executed, it will go line by line as JS is synchronous single threaded language. Lets observe what is happening under call-stack. Above you can see we have set the break-points.</span>

<span class="hljs-comment">// call stack flow -&gt; handlePromise() is pushed -&gt; It will log `Hi` to console -&gt; Next it sees we have await where promise is suppose to be resolved -&gt; So will it wait for promise to resolve and block call stack? </span>
<span class="hljs-comment">//No -&gt; thus handlePromise() execution get suspended and moved out of call stack -&gt; So when JS sees await keyword it suspend the execution of function till promise is resolved -&gt; So `p` will get resolved </span>
<span class="hljs-comment">//after 5 secs so handlePromise() will be pushed to call-stack again after 5 secs. -&gt; But this time it will start executing from where it had left. -&gt; Now it will log 'Hello There!' and 'Promise resolved value!!' -&gt; then it will check whether `p2` is resolved or not -&gt; It will find since `p2` will take 10 secs to resolve </span>
<span class="hljs-comment">//so the same above process will repeat -&gt; execution will be suspended until promise is resolved.</span>

<span class="hljs-comment">//Thus JS is not waiting, call stack is not getting blocked.</span>

<span class="hljs-comment">// Moreover in above scenario what if p1 would be taking 10 secs and p2 5 secs -&gt; even though p2 got resolved earlier but JS is synchronous single threaded language so it will first wait for p1 to be resolved and then will immediately execute all.</span>
</code></pre>
<h2 id="heading-real-world-asyncawait-example">Real-world Async/Await Example</h2>
<p>Imagine a situation in which we asynchronously retrieve data from an external API. We can improve readability and maintainability by streamlining the process with async and await.</p>
<p>fetch() always give us promise and fetch() return a response (It is an response object).</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetch_url = <span class="hljs-string">"any api url"</span>;

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(fetch_url);
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-built_in">console</span>.log(data);
  };
fetchData();
</code></pre>
<h2 id="heading-error-handling">Error Handling</h2>
<p>In async-await, we would use the try-catch block to handle errors instead of the .catch we used with regular Promise. So Basically, there are 2 methods to handle error in JavaScript : .catch method and try-catch method.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetch_url = <span class="hljs-string">"any api url"</span>;

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handlePromise</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> fetch(fetch_url);
    <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> data.json();
    <span class="hljs-built_in">console</span>.log(res);
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-built_in">console</span>.log(err);
  };
};
handlePromise();
<span class="hljs-comment">// In above whenever any error will occur the execution will move to catch block. One could try above with bad url which will result in error.</span>
<span class="hljs-comment">// Other way of handling error:</span>
handlePromise().catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(err)); <span class="hljs-comment">// this will work as handlePromise will return error promise in case of failure.</span>
</code></pre>
<h2 id="heading-promise-versus-asyncawait">Promise versus Async/await :</h2>
<p><strong>Which one should you use?</strong></p>
<ul>
<li><p>async/await is nothing more than syntactical sugar.</p>
</li>
<li><p>In the background, async-await only promises things. Thus, both are the same</p>
</li>
<li><p>async-await is just a new programming style.</p>
</li>
<li><p>A few of Promise's shortcomings, such Promise Chaining, are fixed with async-await.</p>
</li>
<li><p>Additionally, async-await improves readability.</p>
</li>
<li><p>So in a manner, using async-await is always advised.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion:</h2>
<p>To sum up, any JavaScript developer who wants to fully utilise asynchronous programming must understand async and await. Developers can achieve new heights of efficiency and elegance in their code by grasping their complexities and making the most of their potential.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1713789199609/6cb33a6e-f68d-4e84-9259-f7b1878cc0ee.jpeg" alt class="image--center mx-auto" /></p>
<hr />
]]></content:encoded></item><item><title><![CDATA[Promises, Chaining and Error Handling in JavaScript.]]></title><description><![CDATA[Introduction
Asynchronous operations are common in the dynamic field of JavaScript development. Efficiently handling these asynchronous operations is essential to guaranteeing seamless and responsive online applications. Promises are a potent weapon ...]]></description><link>https://blog.siddheshshende.com/promises-chaining-and-error-handling-in-javascript</link><guid isPermaLink="true">https://blog.siddheshshende.com/promises-chaining-and-error-handling-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[WeMakeDevs]]></category><dc:creator><![CDATA[Siddhesh Shende]]></dc:creator><pubDate>Sun, 14 Apr 2024 21:28:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1713129731767/8fc4df66-aef6-43e0-9c8e-4909e77ecc8e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Asynchronous operations are common in the dynamic field of JavaScript development. Efficiently handling these asynchronous operations is essential to guaranteeing seamless and responsive online applications. <mark>Promises</mark> are a potent weapon in the JavaScript toolbox for managing asynchronous processes. Promises offer a methodical approach to handling asynchronous operations and their results, whether they are successful or unsuccessful. We'll explore the foundations of making promises, <mark>chaining</mark> them for smooth operation, and gracefully resolving mistakes in this post. Let's set out to become experts in JavaScript promise construction, chaining, and error management.</p>
<hr />
<h1 id="heading-recognizing-the-creation-of-promises">Recognizing the Creation of Promises</h1>
<p>It's critical to understand the producer-consumer connection when working with promises. A promise object is created by the producer, and the consumer manages whether the promise is eventually fulfilled or not.</p>
<h2 id="heading-making-a-promise">Making a Promise</h2>
<p>We use the built-in Promise constructor in JavaScript to create a promise. We may handle success and failure scenarios with this constructor, which takes a callback function with resolve and reject parameters.</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> cart = [<span class="hljs-string">"pen"</span>, <span class="hljs-string">"bottle"</span>, <span class="hljs-string">"book"</span>];

<span class="hljs-keyword">const</span> promise = createorder(cart);

promise.then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">orderid</span>) </span>{
    <span class="hljs-built_in">console</span>.log(orderid);
    <span class="hljs-comment">// proceedtopayment(orderid);</span>
});   
<span class="hljs-comment">//here, now if we invoke/call the promise with new keyword and passing the functions </span>
<span class="hljs-comment">// with parameters (resolve and reject) and eventually returning it...this is a perfectly valid promise.</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createorder</span>(<span class="hljs-params">cart</span>) </span>{
    <span class="hljs-keyword">const</span> pr = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">resolve, reject</span>) </span>{
<span class="hljs-comment">// Logic to validate and process the cart...</span>
        <span class="hljs-keyword">if</span> (!validateorder()) {
            <span class="hljs-keyword">const</span> err = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"data not found"</span>);
            reject(err);
        }
        <span class="hljs-keyword">const</span> orderid = <span class="hljs-string">"12345"</span>; <span class="hljs-comment">// orderid will be called from database...</span>
        <span class="hljs-keyword">if</span> (orderid) {
<span class="hljs-comment">//here, we can also use settimeout to delay the output(RESOLVE SECTION)</span>
            resolve(orderid);
        }
    });
    <span class="hljs-keyword">return</span> pr;
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">validateorder</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
}
<span class="hljs-comment">// o/p: 12345</span>
</code></pre>
<h2 id="heading-enhancing-asynchronous-operations-with-promise-chaining">Enhancing Asynchronous Operations with Promise Chaining</h2>
<p>A more efficient method for managing several asynchronous task sequentially is made possible by promise chaining. The resolved value from the previous promise is passed to each .then block, allowing data or actions to flow smoothly.</p>
<h2 id="heading-promise-chaining">Promise Chaining :</h2>
<p>Promise chaining improves the readability and maintainability of code by using the output of one promise as the input for the next operation.</p>
<pre><code class="lang-javascript">createOrder(cart)
  .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">orderId</span>) </span>{
    <span class="hljs-comment">// Process the order and return data for chaining</span>
    <span class="hljs-keyword">return</span> proceedToPayment(orderId);
  })
  .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">paymentInfo</span>) </span>{
    <span class="hljs-comment">// Handle payment information</span>
    <span class="hljs-built_in">console</span>.log(paymentInfo);
  })
  .catch(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err</span>) </span>{
    <span class="hljs-comment">// Catch any errors during promise execution</span>
    <span class="hljs-built_in">console</span>.log(err);
  })
</code></pre>
<h2 id="heading-managing-errors-truly">Managing Errors Truly</h2>
<p>A crucial component of promise-based workflows is error handling. We can ensure graceful error management by using .catch to capture any rejections that happen during promise execution.</p>
<h1 id="heading-catch-error-handling">.catch Error Handling</h1>
<p>We may centralise error handling by using the.catch block, which offers a fallback for any promise chain rejections that go unhandled.</p>
<pre><code class="lang-javascript">createOrder(cart)
  .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">orderId</span>) </span>{
    <span class="hljs-comment">// Process the order and return data for chaining</span>
    <span class="hljs-keyword">return</span> proceedToPayment(orderId);
  })
  .catch(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err</span>) </span>{
    <span class="hljs-comment">// Handle errors gracefully</span>
    <span class="hljs-built_in">console</span>.log(err);
  });
<span class="hljs-comment">// we cannot call resolve twice(i.e promises are resolved once only).</span>
</code></pre>
<h2 id="heading-few-key-points-to-understand-the-topic-more-efficiently-are">Few key points to understand the topic more efficiently are:</h2>
<p>1. The new Promise() constructor method can be used to generate a Promise.<br />2. A callback function is an argument passed to this constructor function.<br />3. "Resolve" and "reject" are the two arguments passed to the callback function. JS provides the keywords resolve and reject.<br />4. Our only option is to resolve or reject a promise. There is nothing more that can be done.<br />5. You can also use new Error('error message') to produce an error.<br />6. Another option is to attach a failure callback method, or .catch(), to handle any errors that may arise while the promise chain is being executed.</p>
<p>7. Only .then() errors that are present above it are handled by .catch. Should there be a .then() function behind it, catch will not address any errors related to it, and that .then will always be run.<br />8. In certain cases, it can be helpful if we wish to identify errors for a certain chain link.<br />9. Depending on the requirements, we can have numerous catches, with a general catch coming in the end.<br />10. Never forget to use the promise chain to return a value for the next .then.</p>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>Developing reliable and effective JavaScript apps requires a solid understanding of promise formation, chaining, and error management. Developers can improve code stability and speed asynchronous operations by using these concepts and best practices.</p>
<blockquote>
<p>Read my previous blog part 19 to get better understanding of promises, before this blog....</p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1713128688117/4f4c1353-a4ae-42d1-b3e7-12d8cd7efeb1.jpeg" alt class="image--center mx-auto" /></p>
<hr />
]]></content:encoded></item><item><title><![CDATA[The Role of Promises in Modern JavaScript Development.]]></title><description><![CDATA[Introduction
Asynchronous operations are vital for creating responsive and effective applications when using JavaScript programming. Dealing with asynchronous code is necessary whether handling user interactions, I/O-bound processes, or retrieving da...]]></description><link>https://blog.siddheshshende.com/the-role-of-promises-in-modern-javascript-development</link><guid isPermaLink="true">https://blog.siddheshshende.com/the-role-of-promises-in-modern-javascript-development</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[WeMakeDevs]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[2Articles1Week]]></category><dc:creator><![CDATA[Siddhesh Shende]]></dc:creator><pubDate>Wed, 10 Apr 2024 19:55:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1712778790908/ce8771c6-96b2-496f-82e0-922ab22dcf7b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Asynchronous operations are vital for creating responsive and effective applications when using JavaScript programming. Dealing with asynchronous code is necessary whether handling user interactions, I/O-bound processes, or retrieving data from an external API. But callback functions were previously a major part of controlling asynchronous operations, which resulted in complicated and difficult-to-maintain code structures.<br /><mark>Promises</mark> were proposed as a simpler, more manageable solution to asynchronous operation management in order to overcome these issues. A standardised interface for expressing the eventual success or failure of an asynchronous activity is offered by promises. They make it easier to organise code and handle errors by enabling developers to attach callbacks to handle the outcomes of asynchronous actions.</p>
<hr />
<h2 id="heading-before-promises-the-callback-function">Before Promises: The Callback function</h2>
<p>Let's first review how callbacks were previously used to manage asynchronous actions before delving into Promises. Take into consideration the following hypothetical situation at an online store:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> cart = [<span class="hljs-string">'shoes'</span>, <span class="hljs-string">'pants'</span>, <span class="hljs-string">'kurta'</span>];

<span class="hljs-comment">// Callback approach</span>
createOrder(cart, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  proceedToPayment(orderId);
});
<span class="hljs-comment">// here, we are passing the function to createOrder Api(or function).And,we are blindly trusting the Api.</span>
</code></pre>
<p>The createOrder function in this callback method runs asynchronously and calls the supplied callback function when it's finished. This method creates layered and difficult-to-maintain code structures because it suffers from inversion of control, where the callback function's execution is dependent on the asynchronous operation.</p>
<h2 id="heading-after-introducing-promises">After introducing Promises:</h2>
<p>Callback problems led to the development of Promises as a fix. Promises offer a more organised and controllable approach to working with asynchronous code by representing the eventual success or failure of an asynchronous operation. Let's use Promises to restructure the previous example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> cart = [<span class="hljs-string">'shoes'</span>, <span class="hljs-string">'pants'</span>, <span class="hljs-string">'kurta'</span>];

<span class="hljs-keyword">const</span> promiseRef = createOrder(cart);<span class="hljs-comment">// this promiseRef has access to `then`</span>

<span class="hljs-comment">// {data: undefined}</span>
<span class="hljs-comment">// Initially it will be undefined so below code won't trigger</span>
<span class="hljs-comment">// After some time, when execution has finished and promiseRef has the data then automatically the below line will get triggered.</span>
promiseRef.then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  proceedToPayment(orderId);
});
<span class="hljs-comment">//here, we attached the function to createOrder Api and we can blindly trust promise.</span>
</code></pre>
<p>The createOrder function in this rewritten code instantly returns a Promise object, which stands for the operation's future completion. Using the .then function, we attach a callback that will be triggered after the order creation is finished, which is the fulfilment of the promise.</p>
<h2 id="heading-advantages-of-making-promises">Advantages of Making Promises</h2>
<p>Compared to the typical callback method, promises provide the following advantages:</p>
<ol>
<li><p>Cleaner Code: Promises provide a more linear and legible code structure, which makes asynchronous code easier for developers to understand and maintain. This helps prevent callback hell.</p>
</li>
<li><p>Inversion of Control: Promises help to improve code organisation and maintainability by reading the code more synchronously while maintaining the control flow.</p>
</li>
<li><p>Error Handling: By using the catch method, promises incorporate built-in error handling techniques that enable centralised error management for asynchronous processes.</p>
</li>
<li><p>Promise Chaining: By enabling the sequential chaining of several asynchronous processes, promises help to minimise nesting and enhance the readability of code.</p>
</li>
</ol>
<hr />
<h2 id="heading-what-is-promise">What is Promise??</h2>
<p>-&gt; Promise object is a placeholder which will be filled latter with a value from asynchronous operation.</p>
<p>-&gt; Promise is a container for future value.</p>
<p>-&gt; <strong>A Promise is an object representing the eventual completion or failure of an asynchronous operation.</strong></p>
<ul>
<li><p>Promise Objects are immutable (Upon the fulfilment of the promise, we will have data that we can pass on without fear of data tampering or mutating means promises, once resolved are immutable; thus building up immense trust).</p>
</li>
<li><p>Promise can be resolved only once, either by <code>success</code> or <code>failure</code>.</p>
</li>
<li><p>Promise has 2 main things:</p>
<p>  -&gt;State of Promise(<strong><mark>PromiseState</mark></strong>): It tells us in what state promise is. There are three states in Promise which are</p>
</li>
</ul>
<ol>
<li><p>pending: initial state, neither fulfilled nor rejected.</p>
</li>
<li><p>fulfilled: meaning that the operation was completed successfully.</p>
</li>
<li><p>rejected: meaning that the operation failed.</p>
</li>
</ol>
<blockquote>
<p>As soon as promise is fulfilled/rejected =&gt; It updates the empty object which is assigned undefined in pending state.</p>
</blockquote>
<p>-&gt;Result of Promise(<strong><mark>PromiseResult</mark></strong>): It will store the data whatever it returns.</p>
<h2 id="heading-use-of-promises-in-the-real-world">Use of Promises in the Real World</h2>
<p>Promises are frequently used in conjunction with native browser APIs like fetch, which returns a Promise that represents the response to the HTTP request. They are not simply restricted to asynchronous operations.</p>
<p>As a reference, consider this example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//We will be calling public github api to fetch data i.e https://api.github.com/users/siddheshshende</span>
<span class="hljs-keyword">const</span> GitHubapi = <span class="hljs-string">"https://api.github.com/users/siddheshshende"</span>;
<span class="hljs-keyword">const</span> user = fetch(GitHubapi);
<span class="hljs-comment">// User will be considered as promise.</span>
<span class="hljs-built_in">console</span>.log(user); 
<span class="hljs-comment">//o/p: Promise {&lt;Pending&gt;}</span>
</code></pre>
<p>Fetch(): Fetch() is basically an API given by browsers to us to make external calls.</p>
<p>Now,we can attach callback to above response/promise by using <code>.then</code> only.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//And so, this is how Promise is used by .then method.</span>
<span class="hljs-comment">//It guarantees that it could be resolved only once, either it could be `success` or `failure`</span>
<span class="hljs-keyword">const</span> GitHubapi = <span class="hljs-string">"https://api.github.com/users/siddheshshende"</span>;
<span class="hljs-keyword">const</span> user = fetch(GitHubapi);

user.then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">data</span>) </span>{
  <span class="hljs-built_in">console</span>.log(data);
});
<span class="hljs-comment">// Using .then(), we can control when we want to call/invoke the cb(callback) function.</span>
</code></pre>
<p>Promises are used to <em>solve the problems</em> of callbacks like inversion of control and callback hell (Pyramid of doom).</p>
<ol>
<li><p>.then solves one issue of callback i.e. Inversion of Control.</p>
</li>
<li><p><strong>Promise chaining</strong> solves another issue of callback i.e callback hell.</p>
</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-comment">// Callback Hell Example</span>
createOrder(cart, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">orderId</span>) </span>{
  proceedToPayment(orderId, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">paymentInf</span>) </span>{
    showOrderSummary(paymentInf, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">balance</span>) </span>{
      updateWalletBalance(balance);
    });
  });
});
<span class="hljs-comment">// here,above code is expanding horizontally instead of vertically and this is called pyramid of doom.</span>
<span class="hljs-comment">//So, Promise fixes this issue too using `Promise Chaining`</span>
<span class="hljs-comment">// Example Below is of Promise Chaining.</span>
createOrder(cart)
  .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">orderId</span>) </span>{
    proceedToPayment(orderId);
  })
  .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">paymentInf</span>) </span>{
    showOrderSummary(paymentInf);
  })
  .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">balance</span>) </span>{
    updateWalletBalance(balance);
  });

<span class="hljs-comment">// ⚠️ Common PitFall/mistake many developers make is</span>
<span class="hljs-comment">// they forget to return promise in Promise Chaining</span>
<span class="hljs-comment">// The idea is promise/data returned from one .then become data for next .then</span>
<span class="hljs-comment">// So,</span>
createOrder(cart)
  .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">orderId</span>) </span>{
    <span class="hljs-keyword">return</span> proceedToPayment(orderId);
  })
  .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">paymentInf</span>) </span>{
    <span class="hljs-keyword">return</span> showOrderSummary(paymentInf);
  })
  .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">balance</span>) </span>{
    <span class="hljs-keyword">return</span> updateWalletBalance(balance);
  });
<span class="hljs-comment">// when we don't return the promise in promise chain, then at that time, we can lose</span>
<span class="hljs-comment">// some data. Thus, it is recommended to return promise.</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">// trying to explain the example and show different ways to write Promise.</span>
<span class="hljs-comment">// here, in the below line, createorder Api was returning us a promise.(promise is a variable in this case)</span>
<span class="hljs-keyword">const</span> promise = createOrder(cart);
<span class="hljs-comment">// And then, we were attaching a callback function to createorder Api returned promise.</span>
promise.then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">orderId</span>) </span>{
  proceedToPayment(orderId);
});

<span class="hljs-comment">//another way to write same code   </span>
createOrder(cart).then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">orderId</span>) </span>{
    proceedToPayment(orderId);
  });

<span class="hljs-comment">//another way to write same code is by arrow function.</span>
createOrder(cart)
  .then(<span class="hljs-function">(<span class="hljs-params">orderId</span>) =&gt;</span> proceedToPayment(orderId));
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>JavaScript asynchronous programming has been transformed with promises, which provide a more organised and controllable substitute for conventional callback-based methods. Promises improve code readability, maintainability, and error handling by offering a standardised interface for managing asynchronous processes. Since promises are the basis of many asynchronous patterns and frameworks in the JavaScript ecosystem, understanding them is crucial for current JavaScript developers. Promises make handling asynchronous code easier to understand and less prone to mistakes, enabling programmers to create reliable and effective applications. Thus, utilise Promises in your JavaScript applications to fully utilise asynchronous programming!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712778286879/7721d6da-1f5d-43d4-bae7-261e346725c7.jpeg" alt class="image--center mx-auto" /></p>
<hr />
]]></content:encoded></item><item><title><![CDATA[all about JavaScript's callback function.]]></title><description><![CDATA[Introduction
In the world of JavaScript programming, callback functions are essential, especially when managing asynchronous operations. They are essential tools that enable the execution of code smoothly and efficiently by carrying out activities wi...]]></description><link>https://blog.siddheshshende.com/all-about-javascripts-callback-function</link><guid isPermaLink="true">https://blog.siddheshshende.com/all-about-javascripts-callback-function</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[WeMakeDevs]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Siddhesh Shende]]></dc:creator><pubDate>Tue, 09 Apr 2024 18:33:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1712687133672/e9825739-9c90-4324-a914-11a4aa520c46.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>In the world of JavaScript programming, callback functions are essential, especially when managing asynchronous operations. They are essential tools that enable the execution of code smoothly and efficiently by carrying out activities without stopping the program as a whole.<br />We'll examine the dual nature of <mark>callback functions</mark> in this article, looking at both their advantages and disadvantages. We'll go into details of callback functions and their significance in asynchronous code, as well as how they affect contemporary JavaScript development. We'll also discuss about <mark>Callback Hell </mark> and <mark>Inversion of Control</mark>.</p>
<hr />
<h2 id="heading-callback-functions-an-overview-of-the-good-and-the-bad">Callback Functions: An Overview of the Good and the Bad</h2>
<h3 id="heading-the-good-part-of-callback-functions"><strong>The Good Part of Callback Functions</strong></h3>
<p>In JavaScript, callback functions are crucial when working with asynchronous programming. They ensure seamless and effective performance by enabling the completion of tasks without waiting for the completion of the preceding one.</p>
<p>JavaScript is a synchronous, single-threaded language. However, callbacks allow us to accomplish async things in JavaScript.It is used with closures and often passed as an argument in functional programming.</p>
<p>callback functions are functions that are included as arguments to other functions and then performed when a specified event occurs or an asynchronous operation is completed. In short, <strong>a function passed inside another function as an argument is called as callback function.</strong></p>
<h3 id="heading-how-we-can-create-a-callback-function">How we can create a callback function ??</h3>
<p>\=&gt; however, we will first wrap certain statement inside a function and then, we will passed it onto setTimeout or any other function. Now, job of setTimeout will be to execute the function which is passed after some time(interval).</p>
<p>consider the <em>example</em> which is mentioned below to understand it properly.</p>
<p>Here, we are using the callback method of setTimeout in order to delay the execution.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'you'</span>);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'wealthy'</span>);
}, <span class="hljs-number">5000</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'are'</span>);
<span class="hljs-comment">/* o/p: 
you
are
wealthy (it will get printed after 5 sec)*/</span>
</code></pre>
<h3 id="heading-the-bad-part-of-callback-functions">The Bad Part of Callback Functions</h3>
<p>Callback functions are useful, but they have drawbacks of their own. There are two main problems that come up frequently:</p>
<p><strong>1. Callback Hell:</strong><br />The code can easily become complicated and challenging to manage when working with nested callback methods, and code grows horizontally instead of vertically, resulting in what is sometimes referred to as "Callback Hell" or the "Pyramid of Doom."</p>
<p>When we have a huge codebase and many apis and have dependency on each other, then we fall into callback hell. Then, the code becomes tough to maintain and read.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//E-commerce website example </span>
<span class="hljs-keyword">const</span> products =[<span class="hljs-string">" shoes"</span>, <span class="hljs-string">"airpods"</span>, <span class="hljs-string">"headphones"</span>];

Api.createorder( cart, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    api.paymentprocess(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
        api.ordersummary(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
            api.checkout()
        })
    })
})
<span class="hljs-comment">/*
See the pyramid shape and all the }) at the end repeating? This is affectionately known as callback hell.

The cause of callback hell is when people try to write JavaScript in a way where execution happens visually from top to bottom. 
Lots of people make this mistake! In other languages like C, Ruby or Python there is the expectation that whatever happens on line 1 will finish before the code on line 2 starts running and so on down the file. 
As you will learn, JavaScript is different.
*/</span>
</code></pre>
<p><strong>2. Inversion of Control</strong>:</p>
<p>Because callback functions depend on parent functions to correctly execute them, developers may lose control over the flow of the code as a result of using callback functions. This reliance may result in unexpected mistakes and maintenance issues.</p>
<p>In short, We give authority to the function that calls our callback function; possibly it will never be invoked, or our function may be called twice due to something that is present in their function. <strong>Inversion of control is like that you lose the control of code,when we are using callback.</strong></p>
<pre><code class="lang-javascript">api.createOrder(cart, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  api.proceedToPayment();
});
<span class="hljs-comment">//here, proceedToPayment function is dependent on createOrder function.</span>
<span class="hljs-comment">//So,we don't know proceedToPayment function will get invoked or not.</span>
</code></pre>
<h2 id="heading-how-to-avoid-callback-hell">How to Avoid callback hell ??</h2>
<p>Developers can use more manageable and cleaner code structures by using alternative tactics like async/await syntax, modularization, or promises to avoid slipping into the hole of Callback Hell.</p>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>Although callback functions are necessary for JavaScript asynchronous programming, they have certain drawbacks. It is essential for developers to comprehend callback functions' advantages and disadvantages in order to design effective and manageable code.</p>
<blockquote>
<p>Research Further<br />Visit <a target="_blank" href="http://callbackhell.com">callbackhell.com</a> to learn more about asynchronous programming and callback functions.</p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712686479528/6770acaf-2159-4953-aea8-3c8b31da98f4.jpeg" alt class="image--center mx-auto" /></p>
<hr />
]]></content:encoded></item><item><title><![CDATA[Learning JavaScript's Map(), Filter() and Reduce() Functions.]]></title><description><![CDATA[Introduction
When it comes to developing in JavaScript, knowing  higher order functions is like having a magic wand. The three most powerful ones are  Map, Filter, and Reduce, which give programmers the most flexibility and efficiency when working wi...]]></description><link>https://blog.siddheshshende.com/learning-javascripts-map-filter-and-reduce-functions</link><guid isPermaLink="true">https://blog.siddheshshende.com/learning-javascripts-map-filter-and-reduce-functions</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[WeMakeDevs]]></category><category><![CDATA[2Articles1Week]]></category><dc:creator><![CDATA[Siddhesh Shende]]></dc:creator><pubDate>Sun, 31 Mar 2024 19:38:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1711913556219/69d7fba9-c716-488b-8004-0f876bd218e2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>When it comes to developing in JavaScript, knowing <mark> higher order functions</mark> is like having a magic wand. The three most powerful ones are <mark> Map, Filter, and Reduce</mark>, which give programmers the most flexibility and efficiency when working with arrays. These functions are more than just iteration; they allow for the elegant and precise alteration, selection, and consolidation of data. Come along on an exploration of the complex inner workings of Map, Filter, and Reduce as we reveal their transformational powers and reveal their secrets.</p>
<hr />
<h2 id="heading-1map-function">1.Map Function:</h2>
<p><strong>Transformation of Arrays Meticulously</strong><br />One of the most important JavaScript methods for manipulating arrays is the map() function. It applies a given function to each element iteratively, coordinating the creation of a new array.</p>
<blockquote>
<p>for each loop and map() are almost same. But, the difference is map() creates new array and for each loop doesn't create.</p>
</blockquote>
<p>examples:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">5</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">6</span>];

<span class="hljs-comment">// Example 1: Doubling the Array Elements</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">double</span>(<span class="hljs-params">x</span>) </span>{
  <span class="hljs-keyword">return</span> x * <span class="hljs-number">2</span>;
}
<span class="hljs-keyword">const</span> doubleArr = arr.map(double);
<span class="hljs-built_in">console</span>.log(doubleArr); <span class="hljs-comment">//o/p: [10, 2, 6, 4, 12]</span>

<span class="hljs-comment">//Example 2: Tripling the Array Elements</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">triple</span>(<span class="hljs-params">x</span>) </span>{
  <span class="hljs-keyword">return</span> x * <span class="hljs-number">3</span>;
}
<span class="hljs-keyword">const</span> tripleArr = arr.map(triple);
<span class="hljs-built_in">console</span>.log(tripleArr); <span class="hljs-comment">// o/p:[15, 3, 9, 6, 18]</span>

<span class="hljs-comment">//Example 3: Converting array elements to binary</span>
<span class="hljs-keyword">const</span> arr = [<span class="hljs-number">5</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">6</span>];
<span class="hljs-comment">// Transformation logic:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">binary</span>(<span class="hljs-params">x</span>) </span>{
    <span class="hljs-keyword">return</span> x.toString(<span class="hljs-number">2</span>);
}
<span class="hljs-keyword">const</span> binaryArr = arr.map(binary);

<span class="hljs-comment">// The above code can be rewritten as :</span>
<span class="hljs-keyword">const</span> binaryArr = arr.map(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">binary</span>(<span class="hljs-params">x</span>) </span>{
    <span class="hljs-keyword">return</span> x.toString(<span class="hljs-number">2</span>);
}
<span class="hljs-comment">//Here,to convert number into string or number array into binary array, we use .toString() method with a radix parameter that must be ranging between 2 and 36.</span>
<span class="hljs-comment">// OR -&gt; Arrow function</span>
<span class="hljs-keyword">const</span> binaryArr = arr.map(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x.toString(<span class="hljs-number">2</span>));
<span class="hljs-comment">// o/p: ["101", "1", "11", "10", "110"]</span>
</code></pre>
<p>In simple terms, the map function maps every value and modifies it according to the specified criteria.</p>
<h2 id="heading-2filter-function">2.Filter function:</h2>
<p><strong>Carefully Picking Array Elements</strong></p>
<p>The filter() method makes array filtering easy by creating a new array with elements that satisfy certain requirements.Only values that evaluate to true are stored in an array created by the filter function.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> array = [<span class="hljs-number">5</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">6</span>];
<span class="hljs-comment">// filtering odd values</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isOdd</span>(<span class="hljs-params">x</span>) </span>{
  <span class="hljs-keyword">return</span> x % <span class="hljs-number">2</span>;
}
<span class="hljs-keyword">const</span> oddArr = array.filter(isOdd); <span class="hljs-comment">// o/p:[5,1,3]</span>

<span class="hljs-comment">// Other way of writing the above code using arrow function:</span>
<span class="hljs-keyword">const</span> oddArr = arr.filter(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x % <span class="hljs-number">2</span>);<span class="hljs-comment">//o/p: [5,1,3]</span>

<span class="hljs-comment">//Now,filtering even values</span>
<span class="hljs-keyword">const</span> evenArr = arr.filter(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x % <span class="hljs-number">2</span> === <span class="hljs-number">0</span>);
<span class="hljs-built_in">console</span>.log(evenArr);<span class="hljs-comment">//o/p: [2,6]</span>
</code></pre>
<h2 id="heading-3reduce-function">3.Reduce Function:</h2>
<p><strong>Combining Arrays to Get a Single value</strong></p>
<p>The reduce() method is a fundamental tool that combines array values into a single output and provides a great deal of processing flexibility. It iterates over each element of array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> array = [<span class="hljs-number">5</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">6</span>];
<span class="hljs-comment">// Calculate sum of elements of array - by Non functional programming way</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">findSum</span>(<span class="hljs-params">arr</span>) </span>{
  <span class="hljs-keyword">let</span> sum = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr.length; i++) {
    sum = sum + arr[i];
  }
  <span class="hljs-keyword">return</span> sum;
}
<span class="hljs-built_in">console</span>.log(findSum(array)); <span class="hljs-comment">// o/p:17</span>

<span class="hljs-comment">// now, by reduce function way</span>
<span class="hljs-keyword">const</span> output= arr.reduce(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">acc, curr</span>) </span>{
  acc = acc + curr;
  <span class="hljs-keyword">return</span> accumulator;
}, <span class="hljs-number">0</span>); 
<span class="hljs-comment">//In above example sum was initialized with 0, so over here accumulator also needs to be initialized. </span>
<span class="hljs-comment">//so,the second argument to reduce function represent the initialization value.</span>
<span class="hljs-comment">//for iteration, value needed to be passed in accumulator is 0(i.e it will start iteration from 0th index)</span>
<span class="hljs-comment">//If value is not passed, then index will start from 1.</span>
<span class="hljs-built_in">console</span>.log(output); <span class="hljs-comment">//o/p: 17</span>
</code></pre>
<p>There are 2 parameters in reduce function :</p>
<ol>
<li><p>current(curr):</p>
<p> current represent the current value of array. In the above case, curr refers to arr[i].</p>
</li>
<li><p>accumulator(acc):</p>
<p> It accumulates the callback return value or result. acc is just like a label. In the above case, acc refers to sum.</p>
<pre><code class="lang-javascript"> <span class="hljs-comment">// Another example</span>
 <span class="hljs-comment">// find max inside array: Non functional programming way:</span>
 <span class="hljs-keyword">const</span> array = [<span class="hljs-number">5</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">6</span>];
 <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">findMax</span>(<span class="hljs-params">arr</span>) </span>{
     <span class="hljs-keyword">let</span> max = <span class="hljs-number">0</span>;
     <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr.length; i++ {
         <span class="hljs-keyword">if</span> (arr[i] &gt; max) {
             max = arr[i]
         }
     }
     <span class="hljs-keyword">return</span> max;
 }
 <span class="hljs-built_in">console</span>.log(findMax(array)); <span class="hljs-comment">//o/p: 6</span>

 <span class="hljs-comment">// using reduce</span>
 <span class="hljs-keyword">const</span> output = arr.reduce(<span class="hljs-function">(<span class="hljs-params">acc, current</span>) =&gt;</span> {
     <span class="hljs-keyword">if</span> (current &gt; acc ) {
         acc = current;
     }
     <span class="hljs-keyword">return</span> acc;
 }, <span class="hljs-number">0</span>);
 <span class="hljs-built_in">console</span>.log(output); <span class="hljs-comment">// o/p:6</span>

 <span class="hljs-comment">// acc is just a label which represent the accumulated value till now,</span>
 <span class="hljs-comment">// so we can also label it as max in this case</span>
 <span class="hljs-keyword">const</span> output = arr.reduce(<span class="hljs-function">(<span class="hljs-params">max, current</span>) =&gt;</span> {
     <span class="hljs-keyword">if</span> (current &gt; max) {
         max= current;
     }
     <span class="hljs-keyword">return</span> max;
 }, <span class="hljs-number">0</span>);
 <span class="hljs-built_in">console</span>.log(output); <span class="hljs-comment">//o/p: 6</span>
</code></pre>
</li>
</ol>
<h2 id="heading-tricky-map-question-for-practice">Tricky Map question for Practice:</h2>
<p><strong>Acquiring Expertise in Advanced Approaches</strong></p>
<p>The map function opens up complex functionalities and crosses traditional barriers to allow for complex data transformations.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> users = [
    { <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Alok"</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Raj"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">23</span> },
    { <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Ashish"</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Kumar"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">29</span> },
    { <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Ankit"</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Roy"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">29</span> },
    { <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Pranav"</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Mukherjee"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">50</span> },
];
<span class="hljs-comment">// Get array of full name : ["Alok Raj", "Ashish Kumar", ...]</span>
<span class="hljs-keyword">const</span> fullNameArr = users.map(<span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> user.firstName + <span class="hljs-string">" "</span> + user.lastName);
<span class="hljs-built_in">console</span>.log(fullNameArr); <span class="hljs-comment">// o/p: ["Alok Raj", "Ashish Kumar", ...]</span>

-------------------------------------------------------------------------------

<span class="hljs-comment">// Get the count/report of how many unique people with unique age are there</span>
<span class="hljs-comment">// like: {29 : 2, 75 : 1, 50 : 1}</span>
<span class="hljs-comment">// We should use reduce, why? we want to deduce some information from the array. Basically we want to get a single object as output</span>
<span class="hljs-keyword">const</span> report = users.reduce(<span class="hljs-function">(<span class="hljs-params">acc, curr</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span>(acc[curr.age]) {
        acc[curr.age] = ++ acc[curr.age] ;
    } <span class="hljs-keyword">else</span> {
        acc[curr.age] = <span class="hljs-number">1</span>;
    }

    <span class="hljs-keyword">return</span> acc;  <span class="hljs-comment">//to every time return update object</span>
}, {})
<span class="hljs-built_in">console</span>.log(report) <span class="hljs-comment">// o/p: {29 : 2, 75 : 1, 50 : 1}</span>
</code></pre>
<h2 id="heading-function-chaining">Function Chaining:</h2>
<p><strong>Smooth Integration for Increased Productivity</strong></p>
<p>JavaScript's function chaining feature enables programmers to create solutions that promote readability and efficiency in code.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// First name of all people whose age is less than 30</span>
<span class="hljs-keyword">const</span> users = [
  { <span class="hljs-attr">firstName</span>: <span class="hljs-string">'siddhesh'</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Raj'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">23</span> },
  { <span class="hljs-attr">firstName</span>: <span class="hljs-string">'joy'</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Kumar'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">29</span> },
  { <span class="hljs-attr">firstName</span>: <span class="hljs-string">'pari'</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Roy'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">29</span> },
  { <span class="hljs-attr">firstName</span>: <span class="hljs-string">'Pankaj'</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Mukherjee'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">50</span> },
];

<span class="hljs-comment">// Function chaining</span>
<span class="hljs-keyword">const</span> output = users
  .filter(<span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> user.age &lt; <span class="hljs-number">30</span>)
  .map(<span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> user.firstName);
<span class="hljs-built_in">console</span>.log(output); <span class="hljs-comment">//o/p: ["siddhesh", "joy", "pari"]</span>

<span class="hljs-comment">// Now,Implementing the same logic using reduce() function.</span>
<span class="hljs-keyword">const</span> outputReduce = users.reduce(<span class="hljs-function">(<span class="hljs-params">acc, curr</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (curr.age &lt; <span class="hljs-number">30</span>) {
    acc.push(curr.firstName);
  }
  <span class="hljs-keyword">return</span> acc;
}, []);
<span class="hljs-built_in">console</span>.log(outputReduce); <span class="hljs-comment">//o/p: ["siddhesh", "joy", "pari"]</span>
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">The Map(), Filter() and Reduce() method/function does not execute the function for empty array elements and they do not change the original array also.</div>
</div>

<hr />
<h2 id="heading-conclusion">conclusion:</h2>
<p>JavaScript's Map, Filter, and Reduce methods provide effective array manipulation. Reduce shrinks values, Filter chooses based on criteria, and Map transforms elements. Function chaining, when used with these functions, simplifies the code and improves its readability and scalability. Gaining proficiency with these tools enables developers to take on challenging projects with ease and guarantees beautiful and effective JavaScript programming.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1711912389322/17f46435-6cb8-4596-94af-666112183c28.jpeg" alt class="image--center mx-auto" /></p>
<hr />
]]></content:encoded></item><item><title><![CDATA[Higher-Order Functions in Functional Programming]]></title><description><![CDATA[Introduction: Understanding Functional Programming's Potential
Functional programming  stands out as a shining example of efficiency and elegance in the ever-changing field of software development. The fundamental idea behind higher-order functions i...]]></description><link>https://blog.siddheshshende.com/higher-order-functions-in-functional-programming</link><guid isPermaLink="true">https://blog.siddheshshende.com/higher-order-functions-in-functional-programming</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[WeMakeDevs]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Siddhesh Shende]]></dc:creator><pubDate>Wed, 27 Mar 2024 21:48:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1711575972384/c2c24293-ba5a-4800-844a-b3483871fc47.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction-understanding-functional-programmings-potential">Introduction: Understanding Functional Programming's Potential</h2>
<p><mark>Functional programming </mark> stands out as a shining example of efficiency and elegance in the ever-changing field of software development. The fundamental idea behind higher-order functions is to provide programmers with an extensive toolkit to write clear, modular code. Stay with us, as we explore the world of <mark> higher-order functions </mark> and how they may transform modern development approaches.</p>
<hr />
<h2 id="heading-whats-a-higher-order-function-exactly">What's a Higher Order Function, Exactly?</h2>
<p>Higher-order functions are an essential component of functional programming; they are not just theoretical ideas. However, what sets a higher-order function apart from what it resembles precisely?  </p>
<p>Higher-order functions are essentially regular functions with an additional feature: they can return functions as results or accept other functions as arguments.</p>
<p>This adaptability gives programmers a strong tool for composition and abstraction, enabling flexible and reusable programmes.</p>
<ol>
<li><p>Higher-order functions are basically functions which takes/accepts other functions as arguments and/or returns a function as a result.</p>
</li>
<li><p>The function which is passed into Higher-order function is called as callback function, which is called latter in program.</p>
</li>
<li><p>And all this is possible only due to First class citizens, functions are first class citizens in js.</p>
</li>
</ol>
<p>To give an example, think about this one:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hi'</span>);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">caller</span>(<span class="hljs-params">func</span>) </span>{
  func();
}
caller(greet); <span class="hljs-comment">// Outputs: Hi</span>
</code></pre>
<p>This sample shows how caller is a higher-order function, can be used by passing in greet as an argument and using it within its body. The fact that greet is called a callback function in turn illustrates how dynamic higher-order functions are.</p>
<h2 id="heading-handling-higher-order-function-problems">Handling Higher-Order Function Problems</h2>
<p>Let's attempt to understand the proper way to approach a solution during an interview. I have to find the area, circumference, and diameter  using an array of radius values and store the results in an array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> radius = [<span class="hljs-number">3</span>,<span class="hljs-number">6</span>,<span class="hljs-number">5</span>,<span class="hljs-number">2</span>,];
<span class="hljs-comment">//code to calculate area of a circle.</span>
<span class="hljs-keyword">const</span> calculatearea = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">radius</span>)</span>{
    <span class="hljs-keyword">const</span> output =[];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt;radius.length; i++)  {
output.push(<span class="hljs-built_in">Math</span>.PI* radius[i] * radius[i]);
    }
    <span class="hljs-keyword">return</span> output;
}
<span class="hljs-built_in">console</span>.log(calculatearea(radius));
<span class="hljs-comment">//code to calculate circumference of a circle.</span>
<span class="hljs-keyword">const</span> calculatecircumference = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">radius</span>)</span>{
    <span class="hljs-keyword">const</span> output =[];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt;radius.length; i++)  {
output.push( <span class="hljs-number">2</span> * <span class="hljs-built_in">Math</span>.PI* radius[i]);
    }
    <span class="hljs-keyword">return</span> output;
}
<span class="hljs-built_in">console</span>.log(calculatecircumference(radius));
<span class="hljs-comment">//code to calculate diameter of a circle.</span>
<span class="hljs-keyword">const</span> calculatediameter = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">radius</span>)</span>{
    <span class="hljs-keyword">const</span> output=[];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt;radius.length; i++)  {
output.push( <span class="hljs-number">2</span> * radius[i]);
    }
    <span class="hljs-keyword">return</span> output;
}
<span class="hljs-built_in">console</span>.log(calculatediameter(radius));
<span class="hljs-comment">//output: </span>
<span class="hljs-comment">//[28.274333882308138,113.09733552923255, 78.53981633974483,12.566370614359172]</span>
<span class="hljs-comment">//[18.84955592153876,37.69911184307752,31.41592653589793,12.566370614359172]</span>
<span class="hljs-comment">//[ 6, 12, 10, 4 ]</span>
</code></pre>
<p>This solution behaves flawlessly. But what if our specifications also included the need to calculate anything else? If we kept going in the same direction, we would have redundant code.<br />However, this is where the problem lies: repetition conflicts with the <strong><em>DRY (Don't Repeat Yourself)</em></strong> Principle.</p>
<p>we have to make our code more modular and less repetitive. So, we need to abstract our code/logic due to which we don't require to write the whole code or copy the whole code/function again and again.<br />So, Let's evaluate a more effective and efficient alternatives,now:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> radius = [<span class="hljs-number">3</span>,<span class="hljs-number">6</span>,<span class="hljs-number">5</span>,<span class="hljs-number">2</span>,];

<span class="hljs-keyword">const</span> area = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">radius</span>)</span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Math</span>.PI * radius * radius;
}
<span class="hljs-keyword">const</span> circumference = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">radius</span>)</span>{
    <span class="hljs-keyword">return</span> <span class="hljs-number">2</span> * <span class="hljs-built_in">Math</span>.PI * radius;
}
<span class="hljs-keyword">const</span> diameter = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">radius</span>)</span>{
    <span class="hljs-keyword">return</span> <span class="hljs-number">2</span> * radius;
}

<span class="hljs-keyword">const</span> calculate = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">radius, logic </span>)</span>{
    <span class="hljs-keyword">const</span> output=[];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt;radius.length; i++)  {
output.push(logic(radius[i]));
    }
    <span class="hljs-keyword">return</span> output;
}
<span class="hljs-built_in">console</span>.log(calculate(radius, area));
<span class="hljs-built_in">console</span>.log(calculate(radius, circumference));
<span class="hljs-built_in">console</span>.log(calculate(radius, diameter));
<span class="hljs-comment">//output will be same as mentioned in above code.</span>
</code></pre>
<p>Calculate occurs as a Higher-Order Function in this case. CalculateArea , CalculateCircumference and calculatediameter are some separate functions that we might pass in order to reuse the same logic for different calculations.</p>
<h2 id="heading-making-the-most-of-functional-programmings-power">Making the Most of Functional Programming's Power :</h2>
<p>Furthermore, this method effectively captures the principles of functional programming. We promote modularity and maintainability in our program's code by abstracting logic into distinct functions.</p>
<h3 id="heading-expanding-the-map-function">Expanding the map function :</h3>
<p>Let's continue with our functional approach by turning our calculate function into a <mark>polyfill </mark> for the native map function:</p>
<p>Let's try using the above calculate function changed to a map function. Thus,</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Array</span>.prototype.calculate = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">logic</span>) </span>{
    <span class="hljs-keyword">const</span> output = [];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.length; i++) {
        output.push(logic(<span class="hljs-built_in">this</span>[i]));
    }
    <span class="hljs-keyword">return</span> output;
}
<span class="hljs-built_in">console</span>.log(radius.calculate(area))
<span class="hljs-built_in">console</span>.log(radius.map(area))<span class="hljs-comment">// another way</span>
<span class="hljs-comment">//calculate will be available for all arrays in code. </span>
<span class="hljs-comment">//prototype: when we put something on prototype, it appears on all arrays. </span>
<span class="hljs-comment">//Here,calculate is nothing but polyfill of map function.</span>
<span class="hljs-comment">//console.log(radiusArr.map(area)) == console.log(calculate(radiusArr, area));</span>
</code></pre>
<p><strong>Polyfills</strong> is used to fill the gap between older browers and modern features in js.</p>
<p>polyfills are a piece of code that provides functionality which is not not support by some browers.Popular polyfills exist for features like promises, fetch API , object.assign() etc.....</p>
<hr />
<h2 id="heading-conclusion">conclusion:</h2>
<p>Finally, the key to maximising the potential of functional programming is to become proficient with higher-order functions. We may unleash a world of efficiency, scalability, and elegance in our code by adopting these ideas.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1711575998750/81866d7d-9c5d-4cbe-9e28-524439b27fec.jpeg" alt class="image--center mx-auto" /></p>
<hr />
]]></content:encoded></item><item><title><![CDATA[Understanding SetTimeout() and Concurrency in JavaScript.]]></title><description><![CDATA[Introduction
JavaScript is a fundamental component in the large field of web development, enabling dynamic and interactive experiences on the internet. The setTimeout() method, which is valued for its capacity to run code asynchronously, is essential...]]></description><link>https://blog.siddheshshende.com/understanding-settimeout-and-concurrency-in-javascript</link><guid isPermaLink="true">https://blog.siddheshshende.com/understanding-settimeout-and-concurrency-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[WeMakeDevs]]></category><dc:creator><![CDATA[Siddhesh Shende]]></dc:creator><pubDate>Thu, 21 Mar 2024 20:15:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1711052017247/94d2317f-ce2c-41c0-935a-67b38f2f731b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>JavaScript is a fundamental component in the large field of web development, enabling dynamic and interactive experiences on the internet. The setTimeout() method, which is valued for its capacity to run code asynchronously, is essential to its operation. But beyond the surface simplicity of it all is a hidden problem: <mark> trust issues</mark> with timing accuracy.</p>
<p>The complexities of JavaScript's asynchronous actions get increasingly complex, and developers must grasp the fundamental workings of setTimeout(). In this article, we attempt to solve the puzzles connected to its behaviour and clarify why this so-called dependable function doesn't always perform up to mark.</p>
<p>Come along as we explore the inner workings of <mark>JavaScript concurrency</mark>, examining the nuances of <mark>setTimeout()</mark> and revealing practical solutions to address its trust issues.</p>
<hr />
<h2 id="heading-the-lack-of-clarity-of-settimeout">The lack of clarity of SetTimeout():</h2>
<p>The root of the difficulty is the confusion around the execution timing of the callback function passed to setTimeout(). Consider this code snippet:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Start'</span>);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">cb</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Callback'</span>);
}, <span class="hljs-number">5000</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'End'</span>);
</code></pre>
<p>In this case, one may anticipate the callback code to execute exactly after 5 seconds. However, reality sometimes deviates from this notion.</p>
<h3 id="heading-figuring-out-whats-happening-in-code">figuring out what's Happening in code:</h3>
<ol>
<li><p>Initialization: When setTimeout() is called, JavaScript starts a timer for the specified duration.</p>
</li>
<li><p>Continuation: Meanwhile, the main thread of execution continues without waiting for the timer to expire.</p>
</li>
<li><p>Execution Flow: Code execution proceeds, and some extra tasks are completed, such as printing "Start" and "End".</p>
</li>
<li><p>Callback Queuing: While the main thread is still active, the timer quietly counts down in the background.</p>
</li>
<li><p>Concurrency Model: JavaScript's execution model is single-threaded, which means it can only handle one task at a time.</p>
</li>
<li><p>Delayed execution:Despite the timeout, the callback function waits for its turn in the callback queue until the call stack is cleared.</p>
</li>
</ol>
<h2 id="heading-consequences">consequences :</h2>
<ol>
<li><p>Timing Discrepancy: Because setTimeout() is asynchronous, the callback may run with a delay longer than the provided duration.</p>
</li>
<li><p>Dependence on the Call Stack: Until the call stack is cleared, the callback stays in limbo(confusion), potentially leading to delays.</p>
</li>
<li><p>Concurrency Issues: The JavaScript event loop meticulously supervises task execution, but it cannot overcome the fundamental limits of a single-threaded system.</p>
</li>
</ol>
<h2 id="heading-the-core-of-javascripts-concurrency-model">The core of JavaScript's concurrency model</h2>
<p>JavaScript prioritizes non-blocking activities to ensure responsiveness and efficiency. This requires extreme caution when using asynchronous operations such as setTimeout().</p>
<p>JavaScript was not designed for concurrency,as js is single threaded and synchronous.But, with the help of js Event Loop, it can perform server-side and client-side concurrency.</p>
<p>concurrency model tells us how exactly js handles multiple tasks happening at same time.</p>
<h3 id="heading-practical-views">Practical views:</h3>
<ul>
<li><p>Avoid blocking: Use non-blocking paradigms to avoid stopping the main thread, resulting in smooth application performance.</p>
</li>
<li><p>Optimise responsiveness: Use asynchronous actions wisely to establish a balance between functionality and user experience.</p>
</li>
</ul>
<hr />
<p>In the following example, we are blocking the main thread.Though, first rule of JavaScript is to not block the main thread (because JS is a single threaded language with only one callstack).</p>
<p>we are simulating blocking kind of environment (by suppose million lines of code) by using while loop to create it.</p>
<p>New Date() is a constructor function that returns a specified or current date and time.</p>
<p>getTime() is a method which is used to get timestamp in milliseconds of 'date' object.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1711049984970/38fa79c2-1390-48e2-b48f-36b11c75acc5.jpeg" alt class="image--center mx-auto" /></p>
<h3 id="heading-using-the-power-of-settimeout">Using the Power of setTimeout():</h3>
<p>While setTimeout() remains a useful tool in JavaScript programming, understanding it's oddities is critical for effective use. Understanding the complexities of timing disparities allows developers to use this function with precision and planning.</p>
<h3 id="heading-fine-tuning-execution">Fine-Tuning Execution</h3>
<p><strong>Strategic Delay</strong>: Carefully setting timeouts allows you to prioritise vital tasks while deferring less urgent ones.</p>
<p><strong>Mitigating Risks:</strong> Anticipate timing variances and create code to elegantly handle potential delays.</p>
<hr />
<h2 id="heading-what-if-timeout-0sec">What if timeout = 0sec?</h2>
<p>When setTimeout()'s timeout option is set to 0 seconds, it may appear natural to anticipate the callback function to be executed immediately. However, JavaScript behaves differently as setTimeout() is registered, though it is zero.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Start'</span>);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">cb</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Callback'</span>);
}, <span class="hljs-number">0</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'End'</span>);
<span class="hljs-comment">// o/p: Start End callback</span>
</code></pre>
<p>This use of setTimeout() with a timeout of 0 seconds can help to prioritise crucial tasks while delaying less important ones slightly. Developers can use this technique deliberately to optimise the execution flow of their JavaScript apps, improving overall performance and responsiveness.</p>
<h2 id="heading-conclusion">conclusion</h2>
<p>While setTimeout() may have trust issues with timing precision, understanding how it works enables developers to traverse JavaScript's concurrent world effectively. Programmers can maximise the benefits of asynchronous programming by adopting an adaptable and anticipation attitude.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1711048920264/96fc56b2-3226-4b33-b745-568a69c9a18e.jpeg" alt class="image--center mx-auto" /></p>
<hr />
]]></content:encoded></item><item><title><![CDATA[JS Engine Details in Google's V8 Architecture Explained]]></title><description><![CDATA[Introduction
In the ever-changing world of web development, understanding the complexities of Javascript (JS) and its engines is essential. Today, we'll look at the Javascript Runtime Environment (JRE), which is at the heart of JS execution, as well ...]]></description><link>https://blog.siddheshshende.com/js-engine-details-in-googles-v8-architecture-explained</link><guid isPermaLink="true">https://blog.siddheshshende.com/js-engine-details-in-googles-v8-architecture-explained</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[WeMakeDevs]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Siddhesh Shende]]></dc:creator><pubDate>Mon, 11 Mar 2024 20:32:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1710189091221/60334d71-38d7-4692-ab44-6e1edb0ad406.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>In the ever-changing world of web development, understanding the complexities of Javascript (JS) and its engines is essential. Today, we'll look at the <mark>Javascript Runtime Environment (JRE)</mark>, which is at the heart of JS execution, as well as Google's extraordinary <mark> V8 architecture</mark>, which powers everything from smart watches to web browsers. Join us as we deconstruct the JS engine's key components, including its parsing, compilation, and execution processes, and learn about the powerful V8 architecture. Let us begin on a mission to discover the inner workings of the code that governs the digital universe.</p>
<hr />
<h2 id="heading-js-engine-the-heart-of-javascript-runtime-environment-jre">JS Engine: The Heart of Javascript Runtime Environment (JRE)</h2>
<p>Javascript (JS) is already widespread, powering devices ranging from smartwatches to robots to web browsers, thanks to its Javascript Runtime Environment (JRE). The JRE functions as a comprehensive container, containing everything required to run Javascript code.</p>
<h2 id="heading-figuring-out-jre-components-the-core-element-js-engine">Figuring out JRE Components: The Core Element (JS Engine)</h2>
<p>The JS Engine, often known as the environment's heart, is located at the centre of JRE. It includes critical components like as APIs for interacting with the external environment, event loops, callback queues, microtask queues, and more.</p>
<h2 id="heading-ecmascript-controlling-javascript-rules">ECMAScript: Controlling JavaScript Rules</h2>
<p>JS is governed by ECMAScript and follows a set of standards that are obeyed by all JS engines, including Chakra (Edge), Spidermonkey (Firefox), and the focus of our talk, Google's V8 in Chrome.</p>
<h2 id="heading-understanding-the-javascript-engine">Understanding the JavaScript Engine</h2>
<p>JS Engine is not a physical engine, but rather software written in low-level languages such as C++. It converts high-level JavaScript code into low-level machine code in three steps:   </p>
<ol>
<li><p>parsing</p>
</li>
<li><p>compilation</p>
</li>
<li><p>execution.</p>
</li>
</ol>
<ul>
<li>Parsing: Breaking down the code. During parsing, the code is broken down into tokens. For example, in the sentence "let a = 7," the words "let," "a," "=," and "7" are tokens. A syntax parser also turns the code into an abstract syntax tree (AST), which is similar to a JSON structure.</li>
</ul>
<blockquote>
<p>You can use the <a target="_blank" href="https://astexplorer.net/"><strong>AST Explorer</strong></a> <a target="_blank" href="https://astexplorer.net/">tool to see</a> how code written by you gets parsed into an <em>Abstract Syntax Tree(AST)</em>.</p>
</blockquote>
<ul>
<li><p>JS uses Just-in-Time (JIT) compilation, which combines interpreter and compiler functionality. The AST passes to the interpreter, which converts high-level code to bytecode, while the compiler optimises the code at runtime. JavaScript, a JIT-compiled language, provides the best of both worlds.</p>
</li>
<li><p>Execution: memory and call stack dynamics Execution consists of two important components: Memory Heap (storage for all memory) and Call Stack. A garbage collector implements the Mark and Sweep method to perform memory cleanup.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710188083933/f589813c-f0c3-441d-895f-984dc684a09c.jpeg" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710188131882/67aa12eb-6238-4c8a-aeaa-890545c8ced0.avif" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710188164139/85028995-d5af-4e33-9f55-ce2d369476cd.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-knowing-googles-v8-architecture">Knowing Google's V8 Architecture.</h2>
<p>Google's V8 stands out for its Interpreter (Ignition), Compiler (Turbo Fan), and Garbage Collector (Orinoco). This architecture promotes V8 as a powerful JavaScript engine that can be used on a variety of platforms.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710188021561/65cdc579-7d6c-432c-a5ce-ea32952f9e51.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-companies-are-embracing-js-engines">Companies are embracing JS engines.</h2>
<p>Diverse firms choose different JS engines, each attempting to perfect its implementation. Google's V8, with its unique components, remains a key participant in this competitive landscape.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710188286784/8909b2b8-e3f8-4889-a23c-0a584ce436cd.jpeg" alt class="image--center mx-auto" /></p>
<hr />
]]></content:encoded></item><item><title><![CDATA[Learn Event Loop And Asynchronous JavaScript.]]></title><description><![CDATA[In the dynamic world of web development, the ability to leverage the power of asynchronous JavaScript is essential. This piece of writing takes you on an educational trip, exposing the complexities of Asynchronous JavaScript and simplifying the frequ...]]></description><link>https://blog.siddheshshende.com/learn-event-loop-and-asynchronous-javascript</link><guid isPermaLink="true">https://blog.siddheshshende.com/learn-event-loop-and-asynchronous-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[WeMakeDevs]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Siddhesh Shende]]></dc:creator><pubDate>Sun, 10 Mar 2024 19:56:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1710100415446/7b733112-0df8-4359-ad3c-f2386bd6e748.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the dynamic world of web development, the ability to leverage the power of <mark>asynchronous JavaScript</mark> is essential. This piece of writing takes you on an educational trip, exposing the complexities of Asynchronous JavaScript and simplifying the frequently confusing idea of the <mark>Event Loop.</mark></p>
<hr />
<h2 id="heading-the-basics-call-stack-and-javascript-engine">The Basics: Call Stack and JavaScript Engine.</h2>
<p>Time, tide, and JS(JavaScript) do not wait for anyone. The Call Stack, a key component of the JS Engine, runs any execution context that enters it. But what about the other superpowers the browser has?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710091035888/3156e7cc-5424-42eb-ab44-c24b3663433d.jpeg" alt class="image--center mx-auto" /></p>
<h2 id="heading-web-apis-bringing-call-stack-to-superpowers">Web APIs: Bringing Call Stack to Superpowers</h2>
<p>The browser provides a variety of superpowers, like local storage, timers, geolocation access, fetch and more. Web APIs can help bridge the gap between the call stack and these capabilities.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710091055857/937caab5-62c6-44ec-8b81-8e924fa06be0.jpeg" alt class="image--center mx-auto" /></p>
<h2 id="heading-understanding-web-apis">Understanding web APIs</h2>
<p>Web APIs, which are not inbuilt in JavaScript, enable the call stack to exploit browser superpowers. Examples include setTimeout(), DOM APIs, get(), and localStorage. These functions are accessed via the global object "window".</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Start"</span>);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">cb</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Timer"</span>);
}, <span class="hljs-number">5000</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"End"</span>);
<span class="hljs-comment">// Output: Start, End, Timer (after 5 seconds)</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710097770941/1cf56813-a8c8-42f7-b656-0b8ceed68663.jpeg" alt class="image--center mx-auto" /></p>
<h2 id="heading-the-event-loop-is-introduced">The Event Loop Is Introduced</h2>
<p>How can we ensure that callbacks are executed on time now that we have Web APIs in place? Enter the Event Loop, a gatekeeper that monitors the Callback Queue for pending jobs and moves them to the call stack.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Accessing superpowers through the global object(window)</span>
<span class="hljs-built_in">window</span>.setTimeout(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">cbT</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Callback Timeout"</span>);
}, <span class="hljs-number">5000</span>);

<span class="hljs-built_in">window</span>.fetch(<span class="hljs-string">"https://api.netflix.com"</span>).then(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">cbF</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Callback Netflix"</span>);
});
</code></pre>
<h2 id="heading-demonstrating-the-event-loop">Demonstrating the Event Loop</h2>
<p>Let us deconstruct a code excerpt to see the Event Loop in action. Every step, from creating the Global Execution Context to executing callbacks, is critical to understanding JavaScript's asynchronous behaviour.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Start"</span>);
<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"btn"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">cb</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Callback"</span>);
});
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"End"</span>);
</code></pre>
<h2 id="heading-callback-queue-and-its-importance">Callback Queue and Its Importance</h2>
<p>Why does the callback queue exist? Consider this scenario: a user clicks a button many times. The Event Loop guarantees that all callbacks from those clicks are executed efficiently, avoiding potential delays.</p>
<h2 id="heading-microtask-queue-priority-system">Microtask Queue: Priority System</h2>
<p>Not all tasks are created equally. The Microtask Queue, which has a higher priority than the Callback Queue, handles callback functions from Promises and Mutation Observers quickly. Understanding this priority scheme is critical for efficient code execution.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710098946139/92b20e07-3038-4473-a502-f9544936ef28.gif" alt class="image--center mx-auto" /></p>
<h2 id="heading-fetch-behaviour-and-microtask-priority">Fetch Behaviour and Microtask Priority</h2>
<p>Analyse the behaviour of fetch together with the Microtask Queue. Asynchronous processes, such as waiting for data from external services, show the complex interaction between the Callback Queue and the Microtask Queue.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710098702107/c40294f5-354c-4fee-816d-9bfa639e9e42.jpeg" alt class="image--center mx-auto" /></p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Start"</span>);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">cbT</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"CB Timeout"</span>);
}, <span class="hljs-number">5000</span>);
fetch(<span class="hljs-string">"https://api.netflix.com"</span>).then(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">cbF</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"CB Netflix"</span>);
}); <span class="hljs-comment">// take 2 seconds to bring response</span>
<span class="hljs-comment">// millions lines of code</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"End"</span>);
</code></pre>
<h3 id="heading-observing-event-loop-callback-queue-and-microtask-queue-gif">Observing Event Loop, Callback Queue, and Microtask Queue [GiF]:</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710099268017/44816111-46c7-4cb8-9b38-ede124fa078b.gif" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710099319089/3c15894a-2e0a-49fb-ac92-f9611b3881e2.gif" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710099353454/7da11796-4f6f-4fff-a70c-4c5332e192e1.gif" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710099392882/fe3c9805-ddb8-41ca-94ef-01acda43d889.gif" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710099427691/8eba54cf-1d39-4af1-a9a6-3f6dc5b2f63c.gif" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710099445701/05f6cd55-dc24-4763-a1d0-5176bade0f6d.gif" alt class="image--center mx-auto" /></p>
<p>A mesmerising GIF depicts the complicated dance of the Event Loop, Callback Queue, and Microtask Queue. Gain a better knowledge of how these components interact naturally.</p>
<hr />
<h2 id="heading-conclusion-knowing-asynchronous-javascript">Conclusion: Knowing Asynchronous JavaScript.</h2>
<p>It is critical for developers to understand the complications of Callback and Microtask Queues, as well as the Event Loop. This post attempted to clarify these ideas and lay a solid foundation for understanding JavaScript's asynchronous ecosystem.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710099541289/39a4d2f1-1834-445d-9094-9f91f46619f0.jpeg" alt class="image--center mx-auto" /></p>
<hr />
]]></content:encoded></item><item><title><![CDATA[Callback Functions and Event Listeners in JavaScript.]]></title><description><![CDATA[Introduction
In the fast-paced world of web development, understanding the complexities of JavaScript is essential for creating cutting-edge and responsive applications. This blog post will look into the symbiotic relationship between two essential J...]]></description><link>https://blog.siddheshshende.com/callback-functions-and-event-listeners-in-javascript</link><guid isPermaLink="true">https://blog.siddheshshende.com/callback-functions-and-event-listeners-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[WeMakeDevs]]></category><dc:creator><![CDATA[Siddhesh Shende]]></dc:creator><pubDate>Fri, 23 Feb 2024 18:18:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1708712208895/08235155-7215-46ad-9073-0126df62a9ec.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>In the fast-paced world of web development, understanding the complexities of JavaScript is essential for creating cutting-edge and responsive applications. This blog post will look into the symbiotic relationship between two essential JavaScript concepts: <mark>callback functions and event listeners</mark>. As we delve deeper into these notions, we will discover the transformational powers they provide to developers, enabling a seamless merger of synchronous and asynchronous activities. Join us on this adventure as we explore the potential of callback functions and the efficiency of event listeners, opening up new possibilities in the world of web programming.</p>
<hr />
<h2 id="heading-callback-functions-exploring-asynchronous-possibilities">Callback Functions: Exploring Asynchronous Possibilities</h2>
<p>Functions are more than just lines of code in JavaScript; they are treated as first-class citizens. Consider this: taking a function A and handing it to another function B, where A becomes a callback function. This seemingly simple act allows function B to call function A, opening the door to a world of asynchronous possibilities within a synchronous environment.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Timer"</span>);
}, <span class="hljs-number">1000</span>);
</code></pre>
<p>The first argument is a callback function, while the second is a timer. Callbacks allow JavaScript, which is essentially synchronous and single-threaded, to ignore its nature and perform asynchronous activities.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"timer"</span>);
}, <span class="hljs-number">5000</span>);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">x</span>(<span class="hljs-params">y</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"x"</span>);
  y();
}

x(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">y</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"y"</span>);
});
<span class="hljs-comment">// o/p: x y timer</span>
</code></pre>
<p>x and y are the first functions to appear on the call stack. After execution, they clear the stack. The anonymous function then appears in the stack 5 seconds later, due to setTimeout.  </p>
<p>Understanding the consequences is critical; any operation that blocks the call stack is referred to as blocking the main thread. For example, if x() takes 30 seconds, JavaScript must wait for it to complete because it only has one call stack and one main thread. Always use async for time-consuming operations like setTimeout.</p>
<h2 id="heading-understanding-callbacks-another-example">Understanding Callbacks: Another Example</h2>
<p>Let's look at another example to further understand the callback concept:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printStr</span>(<span class="hljs-params">str, cb</span>) </span>{
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(str);
        cb();
    }, <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">100</span>) + <span class="hljs-number">1</span>)
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printAll</span>(<span class="hljs-params"></span>) </span>{
    printStr(<span class="hljs-string">"A"</span>, <span class="hljs-function">() =&gt;</span> {
        printStr(<span class="hljs-string">"B"</span>, <span class="hljs-function">() =&gt;</span> {
            printStr(<span class="hljs-string">"C"</span>, <span class="hljs-function">() =&gt;</span> {})
        })
    })
}

printAll(); 
<span class="hljs-comment">// o/p: A B C // in order</span>
</code></pre>
<h2 id="heading-using-the-power-of-event-listeners">Using the Power of Event Listeners</h2>
<p><strong>Implementing a Basic Event Listener.</strong></p>
<p>Moving beyond callbacks, let's look at Event Listeners. Consider building a button in HTML and assigning an event to it.</p>
<pre><code class="lang-xml"><span class="hljs-comment">&lt;!-- index.html --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"clickMe"</span>&gt;</span>Click Me!<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>In your JavaScript file:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// in index.js</span>
<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"clickMe"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">xyz</span>(<span class="hljs-params"></span>)</span>{
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Button clicked"</span>);
});
</code></pre>
<h3 id="heading-taking-it-up-a-peak-increase-counter-button">Taking it Up a Peak: Increase Counter Button</h3>
<p>To improve user involvement, let's build an increment counter button:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>;
<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"clickMe"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">xyz</span>(<span class="hljs-params"></span>)</span>{ 
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Button clicked"</span>, ++count);
});
</code></pre>
<h3 id="heading-using-closures-for-data-abstractionnow">Using Closures for Data Abstraction,now.</h3>
<p>Closures are a cleaner way to abstract data.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">attachEventList</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>;
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"clickMe"</span>)
     .addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">xyz</span>(<span class="hljs-params"></span>)</span>{ 
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Button clicked"</span>, ++count);
    });
}
attachEventList();
</code></pre>
<h2 id="heading-event-listener-demo-efficient-resource-management">Event Listener Demo: Efficient Resource Management.</h2>
<p>Event listeners, while effective, might be resource-intensive owing to closures. Even if the call stack is empty, the EventListener may not free the memory allocated to count. To optimize, event listeners should be removed when they are no longer required, avoiding excessive memory usage.</p>
<blockquote>
<p>Garbage Collection and removeEventListeners is performed.</p>
<p>onClick, onHover, onScroll etc all in a page can slow it down heavily.</p>
</blockquote>
<hr />
<h2 id="heading-conclusion-understanding-the-system-of-callbacks-and-event-listeners">Conclusion: Understanding the System of Callbacks and Event Listeners</h2>
<p>Finally, knowing the interaction of callback functions and event listeners not only unlocks JavaScript's full capabilities, but also assures efficient resource management. Mastering these concepts allows developers to create flawless and responsive online apps, which is a huge step forward in the pursuit of web development excellence.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1708711708071/71072137-59ee-42e8-9c98-6dc95716c3a4.jpeg" alt class="image--center mx-auto" /></p>
<hr />
]]></content:encoded></item><item><title><![CDATA[Elevate Code Skills: First Class Functions in JavaScript]]></title><description><![CDATA[Introduction:
JavaScript, the language that gives life to the web, is a domain where functions reign supreme. These functions, known as the "heartbeat" of JavaScript, significantly impact code dynamics. In this adventure across the code cosmos, let u...]]></description><link>https://blog.siddheshshende.com/elevate-code-skills-first-class-functions-in-javascript</link><guid isPermaLink="true">https://blog.siddheshshende.com/elevate-code-skills-first-class-functions-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[WeMakeDevs]]></category><dc:creator><![CDATA[Siddhesh Shende]]></dc:creator><pubDate>Mon, 19 Feb 2024 17:54:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1708364806525/11120b77-631b-4f21-83c0-531ed5fe2569.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction:</h2>
<p>JavaScript, the language that gives life to the web, is a domain where functions reign supreme. These functions, known as the "heartbeat" of JavaScript, significantly impact code dynamics. In this adventure across the code cosmos, let us discover the enchantment hidden inside <mark> First Class Functions</mark> and <mark>Anonymous Functions</mark>.</p>
<hr />
<h2 id="heading-understanding-functional-statements">Understanding Functional Statements:</h2>
<p>Function statements serve as the core building blocks of JavaScript. Consider the following example.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">a</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello"</span>);
}
a(); <span class="hljs-comment">// Hello</span>
</code></pre>
<p>a() is a function statement that produces the intended output when invoked.</p>
<h2 id="heading-understanding-function-expressions">Understanding Function Expressions:</h2>
<p>Function expressions involve applying a function to a variable while treating functions as values.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> b = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello"</span>);
}
b();
</code></pre>
<p>In this case, b() is a function expression that provides flexibility and serves as a value.</p>
<h2 id="heading-addressing-the-hoisting-dilemma">Addressing the Hoisting Dilemma</h2>
<p>The notion of Hoisting helps you understand the difference between function statements and expressions. Consider this specific example</p>
<pre><code class="lang-javascript">a(); <span class="hljs-comment">// "Hello A"</span>
b(); <span class="hljs-comment">// TypeError</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">a</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello A"</span>);
}
<span class="hljs-keyword">var</span> b = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello B"</span>);
}
<span class="hljs-comment">// Why? During memory creation phase a is created in memory and function assigned to a. </span>
<span class="hljs-comment">//But b is created like a variable (b:undefined) and until code reaches the function()  part, it is still undefined. So it cannot be called.</span>
</code></pre>
<p>Hoisting treats function statements uniquely than expressions, which affects their accessibility.</p>
<h2 id="heading-understanding-function-declarations">Understanding Function Declarations :</h2>
<p>Function declarations are an alternate name for function statements, which expands your coding vocabulary.</p>
<h2 id="heading-enigma-of-anonymous-functions">Enigma of Anonymous Functions:</h2>
<p>A function without name is anonymous function. They don't have their identity and they are used in place where functions are used as values.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{

}
<span class="hljs-comment">// this is going to throw Syntax Error - Function Statement requires function name.</span>
</code></pre>
<p>An anonymous function without code returns an error due to a lack of identity. They find benefit when functions are used as values, as in function expressions.</p>
<h2 id="heading-named-function-expressions-balancing-identity">Named Function Expressions: Balancing Identity.</h2>
<p>Same as Function Expression but function has a name instead of being anonymous.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> b = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">xyz</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'b called'</span>);
};
b(); <span class="hljs-comment">// "b called"</span>
xyz(); <span class="hljs-comment">// Throws ReferenceError:xyz is not defined.</span>
<span class="hljs-comment">// xyz function is not created in global scope. So it can't be called.</span>
</code></pre>
<p>Named functions, on the other hand, have a limited scope, which limits their global accessibility.</p>
<h2 id="heading-learning-parameters-and-arguments">Learning Parameters and Arguments</h2>
<p>Understanding the distinction between parameters and arguments is crucial.</p>
<pre><code class="lang-javascript"> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">info</span>(<span class="hljs-params">name, age</span>)</span>{ <span class="hljs-comment">// labels/identifiers are like parameters</span>
    <span class="hljs-built_in">console</span>.log (<span class="hljs-string">"Hi "</span>+ name + <span class="hljs-string">",you are "</span> + age +<span class="hljs-string">" years old now."</span>);
}
info(<span class="hljs-string">"Siddhesh"</span>, <span class="hljs-number">20</span>);<span class="hljs-comment">// arguments are values passed inside function call</span>
<span class="hljs-comment">// output: Hi Siddhesh,you are 20 years old now.</span>
</code></pre>
<p>Here, name and age are parameters and Siddhesh and 20 are arguments, which represent values in a function call.</p>
<h2 id="heading-understanding-first-class-functions-or-first-class-citizens">Understanding first class functions or First Class Citizens:</h2>
<p>Functions can be passed as arguments or returned from a function. The ability to utilise functions as values is known as first-class function. It is a programming idea that is also accessible in a few other languages.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> b = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">param1</span>) </span>{
  <span class="hljs-built_in">console</span>.log(param1); 
};
b(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
});<span class="hljs-comment">// output: f() {}</span>

<span class="hljs-comment">// Other way of doing the same thing.But, it is named.</span>
<span class="hljs-keyword">var</span> b = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">param1</span>) </span>{
  <span class="hljs-built_in">console</span>.log(param1);
};
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">xyz</span>(<span class="hljs-params"></span>) </span>{}
b(xyz); <span class="hljs-comment">// output: f xyz() {} </span>


<span class="hljs-comment">// again doing the same thing. we can return a function from a function:</span>
<span class="hljs-keyword">var</span> b = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">param1</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">xyz</span>(<span class="hljs-params"></span>) </span>{
};
};
<span class="hljs-built_in">console</span>.log(b()); <span class="hljs-comment">//we log the entire fun within b. output: f xyz() {}</span>
</code></pre>
<hr />
<h2 id="heading-conclusion-improving-your-javascript-understanding">Conclusion: Improving Your JavaScript Understanding</h2>
<p>In the complex world of JavaScript, understanding every aspect of functions, from statements to expressions, and embracing the power of First Class Functions is critical. These notions not only improve code readability, but they also pave the way for new development approaches.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1708364936801/7ecd513f-da11-4bfb-a1b2-fd004a97ab55.jpeg" alt class="image--center mx-auto" /></p>
<hr />
]]></content:encoded></item><item><title><![CDATA[The Power of Closures in JavaScript.]]></title><description><![CDATA[Introduction
In the fast-paced world of JavaScript, knowing the idea of closures is similar to discovering a hidden treasure vault of programming skill. Closures, an essential component of JavaScript's  lexical scope environment, are the key to effic...]]></description><link>https://blog.siddheshshende.com/the-power-of-closures-in-javascript</link><guid isPermaLink="true">https://blog.siddheshshende.com/the-power-of-closures-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[WeMakeDevs]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Siddhesh Shende]]></dc:creator><pubDate>Sun, 04 Feb 2024 10:21:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1707041813932/c24da69f-6d0e-440d-aabe-ca7f46ccfd52.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>In the fast-paced world of JavaScript, knowing the idea of <mark>closures</mark> is similar to discovering a hidden treasure vault of programming skill. Closures, an essential component of JavaScript's <mark> lexical scope</mark> environment, are the key to efficient code structuring and sophisticated functionality.</p>
<hr />
<h2 id="heading-learning-lexical-scopes-and-closures-in-javascript">Learning Lexical Scopes and Closures in JavaScript.</h2>
<p>JavaScript's lexical scope environment opens the way for a unique approach for variable access within functions. When a function seeks a variable, it searches its local memory. If the variable cannot be found, the function searches the lexical parent's memory. This complex procedure produces closures, as shown in the code sample below.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">x</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> a = <span class="hljs-number">7</span>;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">y</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(a);
    }
    <span class="hljs-keyword">return</span> y;
}

<span class="hljs-keyword">var</span> z = x();
<span class="hljs-built_in">console</span>.log(z);  <span class="hljs-comment">// The value of z is the entire code of function y.</span>
</code></pre>
<p>This code not only returns the function y, but also encapsulates the whole closure, including function y and its lexical scope, in the variable z. As a result, when z is used elsewhere in the code, it keeps the memory of var a within x().</p>
<h3 id="heading-studying-closure-with-another-example">Studying Closure with Another Example.</h3>
<p>To further understand the notion, consider the following example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">z</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> b = <span class="hljs-number">900</span>;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">x</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">var</span> a = <span class="hljs-number">7</span>;
        <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">y</span>(<span class="hljs-params"></span>) </span>{
            <span class="hljs-built_in">console</span>.log(a, b);
        }
        y();
    }
    x();
}

z();  
<span class="hljs-comment">// Outputs: </span>
<span class="hljs-number">7</span> 
<span class="hljs-number">900</span>
</code></pre>
<p>In simple terms, a closure is a function that has access to its outside function scope even after the function has completed. This inherent characteristic enables closures to retrieve and access variables and argument references from their outer function even after the function has returned.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1707041108231/ad46323a-e8aa-41c3-aef8-ded2d9253e87.jpeg" alt class="image--center mx-auto" /></p>
<h2 id="heading-advantages-of-closures">Advantages of Closures:</h2>
<ul>
<li><p>Module Design Pattern.</p>
</li>
<li><p>Currying.</p>
</li>
<li><p>Memorization.</p>
</li>
<li><p>Data Hiding and Encapsulation.</p>
</li>
<li><p>setTimeouts, etc.</p>
</li>
</ul>
<h2 id="heading-disadvantages-of-closures">Disadvantages of closures:</h2>
<ul>
<li><p>excessive memory consumption.</p>
</li>
<li><p>Possible issues include memory leaks and browser freezing.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1707041289733/34f9738b-05a7-4c2d-b00b-934d6800afd4.jpeg" alt class="image--center mx-auto" /></p>
</li>
</ul>
<hr />
]]></content:encoded></item><item><title><![CDATA[JavaScript Scope War: Showdown Between Block Scope and Shadowing...]]></title><description><![CDATA[Introduction
JavaScript's dynamic capabilities keep developers on their toes. Two key aspects demand our attention as we work to understand the complexities of JavaScript: Block Scope and Shadowing. Understanding these ideas is essential for not only...]]></description><link>https://blog.siddheshshende.com/javascript-scope-war-showdown-between-block-scope-and-shadowing</link><guid isPermaLink="true">https://blog.siddheshshende.com/javascript-scope-war-showdown-between-block-scope-and-shadowing</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[WeMakeDevs]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Siddhesh Shende]]></dc:creator><pubDate>Mon, 29 Jan 2024 11:57:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706529361956/142f9b5a-dbd4-4e6d-a563-4ee92f277d60.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>JavaScript's dynamic capabilities keep developers on their toes. Two key aspects demand our attention as we work to understand the complexities of JavaScript: <mark>Block Scope and Shadowing</mark>. Understanding these ideas is essential for not only producing better code, but also reaching JavaScript's full potential. So, let's dig deep into the world of Block Scope and Shadowing to improve our coding abilities.</p>
<hr />
<h2 id="heading-understanding-the-basics-what-is-a-block-in-javascript">Understanding the Basics: What is a Block in JavaScript?</h2>
<p>In JavaScript, a block, also known as a compound statement, is a powerful tool for grouping statements together. These statements are enclosed in curly braces {...}.</p>
<pre><code class="lang-javascript">{
    <span class="hljs-keyword">var</span> a = <span class="hljs-number">10</span>;
    <span class="hljs-keyword">let</span> b = <span class="hljs-number">20</span>;
    <span class="hljs-keyword">const</span> c = <span class="hljs-number">30</span>;
    <span class="hljs-comment">// Let and const are hoisted in Block scope,</span>
    <span class="hljs-comment">// While var is hoisted in Global scope.</span>
}
</code></pre>
<h3 id="heading-exploring-block-scope-and-accessibility">Exploring Block Scope and Accessibility.</h3>
<pre><code class="lang-javascript">{
    <span class="hljs-keyword">var</span> a = <span class="hljs-number">10</span>;
    <span class="hljs-keyword">let</span> b = <span class="hljs-number">20</span>;
    <span class="hljs-keyword">const</span> c = <span class="hljs-number">30</span>;
}
<span class="hljs-built_in">console</span>.log(a); <span class="hljs-comment">// 10</span>
<span class="hljs-built_in">console</span>.log(b); <span class="hljs-comment">// Uncaught ReferenceError: b is not defined</span>
</code></pre>
<h2 id="heading-learning-the-reason-behind-it">Learning the Reason behind It</h2>
<p>Variables b and c in the <strong>BLOCK SCOPE</strong> field are initialised as undefined due to hoisting, and they exist in a separate memory area known as a block. Meanwhile, variable an is stored in the global scope. This basic difference means that let and const are <strong>BLOCK SCOPED</strong>, meaning they are only available within the block in which they are defined, but var is global and accessible elsewhere.</p>
<h2 id="heading-figuring-out-the-secret-what-is-shadowing">Figuring out the Secret: What is Shadowing???</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> a = <span class="hljs-number">100</span>;
{
    <span class="hljs-keyword">var</span> a = <span class="hljs-number">10</span>; <span class="hljs-comment">// Same name as global var</span>
    <span class="hljs-keyword">let</span> b = <span class="hljs-number">20</span>;
    <span class="hljs-keyword">const</span> c = <span class="hljs-number">30</span>;
    <span class="hljs-built_in">console</span>.log(a); <span class="hljs-comment">// 10</span>
    <span class="hljs-built_in">console</span>.log(b); <span class="hljs-comment">// 20</span>
    <span class="hljs-built_in">console</span>.log(c); <span class="hljs-comment">// 30 </span>
}
<span class="hljs-built_in">console</span>.log(a); <span class="hljs-comment">// 10, modifying the value of the global "a"</span>
</code></pre>
<p>When using var, if another variable with the same name exists outside the block, the variable inside the block takes place of the external one. This problem does not occur with let or const.</p>
<h2 id="heading-understanding-the-behavior-of-let-and-const">Understanding the Behavior of Let and Const.</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> b = <span class="hljs-number">100</span>;
{
    <span class="hljs-keyword">var</span> a = <span class="hljs-number">10</span>;
    <span class="hljs-keyword">let</span> b = <span class="hljs-number">20</span>;
    <span class="hljs-keyword">const</span> c = <span class="hljs-number">30</span>;
    <span class="hljs-built_in">console</span>.log(b); <span class="hljs-comment">// 20</span>
}
<span class="hljs-built_in">console</span>.log(b); <span class="hljs-comment">// 100, separate spaces for both b's (Block: 20, Script: 100)</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706528592998/165212de-9c14-4535-9e2f-86f9ece4691c.jpeg" alt class="image--center mx-auto" /></p>
<h2 id="heading-understanding-functions-block-scope">Understanding Function's Block Scope.</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> c = <span class="hljs-number">100</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">x</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> c = <span class="hljs-number">10</span>;
    <span class="hljs-built_in">console</span>.log(c); <span class="hljs-comment">// 10</span>
}
x();
<span class="hljs-built_in">console</span>.log(c); <span class="hljs-comment">// 100</span>
</code></pre>
<h2 id="heading-take-precautions-of-illegal-shadowing">Take precautions of Illegal Shadowing.</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-number">20</span>;
{
    <span class="hljs-keyword">var</span> a = <span class="hljs-number">20</span>;
}
<span class="hljs-comment">// Uncaught SyntaxError: Identifier 'a' has already been declared</span>
</code></pre>
<p>Remember that it is not OK to use shadow let with var, but the converse is true. In addition, let can shadow another let, whereas var cannot.</p>
<hr />
<p>Understanding Block Scope and Shadowing is critical in JavaScript, where correctness is everything. Understanding these notions enables developers to design strong, error-free programs.</p>
<p>Stay Tuned!! Happy Learning!!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706528163592/c28ffc8e-a9ee-48ee-8316-8bc12ff6f3df.jpeg" alt class="image--center mx-auto" /></p>
<hr />
]]></content:encoded></item><item><title><![CDATA[How to Use Let, Const and Var to Conquer the Temporal Dead Zone in JavaScript.]]></title><description><![CDATA[Introduction
Developers frequently face issues due to JavaScript's dynamic and adaptable nature. Some of the complexities include the distinctions between let and const declarations, as well as the Temporal Dead Zone (TDZ). In this guide, we'll look ...]]></description><link>https://blog.siddheshshende.com/how-to-use-let-const-and-var-to-conquer-the-temporal-dead-zone-in-javascript</link><guid isPermaLink="true">https://blog.siddheshshende.com/how-to-use-let-const-and-var-to-conquer-the-temporal-dead-zone-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[WeMakeDevs]]></category><category><![CDATA[2Articles1Week]]></category><dc:creator><![CDATA[Siddhesh Shende]]></dc:creator><pubDate>Sun, 28 Jan 2024 06:51:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706424595973/1a873111-92d7-43a9-92f2-f212150acad4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>Developers frequently face issues due to JavaScript's dynamic and adaptable nature. Some of the complexities include the distinctions between let and const declarations, as well as the <mark>Temporal Dead Zone (TDZ)</mark>. In this guide, we'll look at the intricacies, like hoisting mechanisms, TDZ, and typical problems. Let's go on our journey to improve our JavaScript skills.</p>
<hr />
<h3 id="heading-understanding-hoisting-in-declarations">Understanding Hoisting in Declarations.</h3>
<p>Understanding the differences between <mark>let, const and var</mark> is critical in the ever-changing JavaScript ecosystem. Let's go into the minute details of hoisting, with a special emphasis on let and const.</p>
<p><strong>Hoisting basic concepts:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(a); <span class="hljs-comment">// ReferenceError: Cannot access 'a' before initialization</span>
<span class="hljs-built_in">console</span>.log(b); <span class="hljs-comment">// prints undefined as expected</span>
<span class="hljs-keyword">let</span> a = <span class="hljs-number">10</span>;
<span class="hljs-keyword">var</span> b = <span class="hljs-number">15</span>;
<span class="hljs-built_in">console</span>.log(a); <span class="hljs-comment">// 10</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">window</span>.a); <span class="hljs-comment">// undefined</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">window</span>.b); <span class="hljs-comment">// 15</span>
</code></pre>
<p>Despite appearances, let is hoisted; however, understanding its behaviour needs going into the initialization process. During the hoisting stage, both a and b are initially set to undefined. However, key difference emerges: var b is in the GLOBAL storage space, whereas let an is in a separate memory object called script.</p>
<h3 id="heading-temporal-dead-zone-exposed">Temporal Dead Zone Exposed</h3>
<p>The Temporal Dead Zone (TDZ) occurs between hoisting and initialising a let variable. Any line preceding "let a = 10" denotes the TDZ of variable 'a'.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">window</span>.a); <span class="hljs-comment">// undefined</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">window</span>.b); <span class="hljs-comment">// 15</span>
</code></pre>
<p>Because 'a' is not globally accessible, attempting to access it in window or this context returns undefined, much like accessing an undeclared variable like 'window.x'</p>
<h3 id="heading-syntax-and-type-errors">Syntax and Type Errors</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-number">10</span>;
<span class="hljs-keyword">let</span> a = <span class="hljs-number">100</span>;  <span class="hljs-comment">// SyntaxError: Duplicate declaration</span>
</code></pre>
<p>A SyntaxError is raised when let variable is attempted to be redeclared inside of the same scope. This also applies to combining declarations of the same name i.e let and var.</p>
<p>Constant(Const): The Strict Guardian.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> b;
b = <span class="hljs-number">10</span>; <span class="hljs-comment">// SyntaxError: Missing initializer in const declaration</span>
</code></pre>
<p>Unlike let, const requires initialization during declaration. Attempting to assign a value later to a const variable results in a TypeError.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> b = <span class="hljs-number">100</span>;
b = <span class="hljs-number">1000</span>; <span class="hljs-comment">// TypeError: Assignment to constant variable</span>
</code></pre>
<h3 id="heading-types-of-javascript-errors">Types of JavaScript Errors:</h3>
<p>JavaScript errors come in three flavours: syntax, reference, and type.</p>
<p>Understanding these errors is critical for creating reliable programming.</p>
<p><strong>Guidelines for Declarations:</strong></p>
<p>In your coding journey, consider the following practices.</p>
<ol>
<li><p>Use const wherever possible to ensure immutability.</p>
</li>
<li><p>If not, use let over var for better scope.</p>
</li>
<li><p>Declare and initialise all variables with let at the top to reduce the Temporal Dead Zone window.</p>
</li>
</ol>
<hr />
<h3 id="heading-conclusion">Conclusion:</h3>
<p>Finally, understanding the aspects of let and const declarations, as well as the Temporal Dead Zone, helps you write cleaner and more error-resistant JavaScript code.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706422528229/570f1fe6-bb5a-4b1a-a0b0-732cd116568d.jpeg" alt class="image--center mx-auto" /></p>
<hr />
]]></content:encoded></item><item><title><![CDATA[JavaScript's Scope Chain and Lexical Environment: An Overview]]></title><description><![CDATA[Introduction
JavaScript, the driving force behind dynamic web pages, contains an interesting interplay between  scope, the scope chain, and the lexical environment. Understanding these notions is critical for mastering the language and writing effici...]]></description><link>https://blog.siddheshshende.com/javascripts-scope-chain-and-lexical-environment-an-overview</link><guid isPermaLink="true">https://blog.siddheshshende.com/javascripts-scope-chain-and-lexical-environment-an-overview</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[WeMakeDevs]]></category><category><![CDATA[2Articles1Week]]></category><dc:creator><![CDATA[Siddhesh Shende]]></dc:creator><pubDate>Sat, 27 Jan 2024 15:10:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706367972903/6df73310-1b3f-4a99-ae60-3d400a9e0f9b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>JavaScript, the driving force behind dynamic web pages, contains an interesting interplay between <mark> scope, the scope chain, and the lexical environment</mark>. Understanding these notions is critical for mastering the language and writing efficient, error-free code. In this investigation, we will unravel the mysteries of the <mark>Scope Chain, Scope, and Lexical Environment</mark>, figuring out the complexities that regulate variable access and execution context.</p>
<hr />
<h3 id="heading-understanding-the-basics-scope-and-lexical-environment">Understanding the Basics: Scope and Lexical Environment.</h3>
<p>In the world of Javascript, scope is tightly tied to the Lexical Environment. Let's look at some examples to shed light on this link.</p>
<p><strong>Case 1: Accessing the Global Scope.</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">a</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(b); <span class="hljs-comment">// 10</span>
  <span class="hljs-comment">// Instead of printing undefined, it prints 10. This function can access the variable b outside its scope.</span>
}
<span class="hljs-keyword">var</span> b = <span class="hljs-number">10</span>;
a();
</code></pre>
<p><strong>Case 2: Nesting and Global Scope Access.</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">a</span>(<span class="hljs-params"></span>) </span>{
  c();
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">c</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(b); <span class="hljs-comment">// 10</span>
  }
}
<span class="hljs-keyword">var</span> b = <span class="hljs-number">10</span>;
a();
</code></pre>
<p><strong>Case 3: Local Priority Over Global</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">a</span>(<span class="hljs-params"></span>) </span>{
  c();
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">c</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> b = <span class="hljs-number">100</span>;
    <span class="hljs-built_in">console</span>.log(b); <span class="hljs-comment">// 100</span>
  }
}
<span class="hljs-keyword">var</span> b = <span class="hljs-number">10</span>;
a();
</code></pre>
<p><strong>Case 4: Global vs. Local Scopes</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">a</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> b = <span class="hljs-number">10</span>;
  c();
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">c</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(b); <span class="hljs-comment">// 10</span>
  }
}
a();
<span class="hljs-built_in">console</span>.log(b); <span class="hljs-comment">// Error, Not Defined</span>
</code></pre>
<h3 id="heading-understanding-the-output">Understanding the output:</h3>
<p>In Case 1, the function 'a' has access to the variable 'b' from the global scope. Case 2 demonstrates that the global scope variable can be accessed from within nested functions. Moving on to Case 3, a local variable takes precedence over a global one, yielding a value of 100. Case 4 shows that a function can access a global variable, but the global execution context cannot access any local variables.</p>
<h3 id="heading-understanding-the-execution-context">Understanding the Execution Context</h3>
<p>To summarize the points in terms of execution context, look at the call stack:</p>
<p><strong>[GEC, a(), c()]</strong>.</p>
<p>Let us allocate memory portions to each execution context in the call stack.</p>
<ul>
<li><p><code>c()</code>: <code>[lexical environment pointer pointing to a()]</code></p>
</li>
<li><p><code>a()</code>: <code>[b:10, c:{}, [lexical environment pointer pointing to GEC]]</code></p>
</li>
<li><p><code>GEC</code>: <code>[a:{}, [lexical environment pointer pointing to null]]</code></p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706366873323/5ab902a7-fca7-4d84-b827-d167f3b9ae3e.jpeg" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706366982859/ef6bc6b6-1f72-4a34-9c0c-3df5a3b9c083.jpeg" alt class="image--center mx-auto" /></p>
<h3 id="heading-simplifying-the-lexical-environment">simplifying the Lexical Environment:</h3>
<p>The lexical environment is a combination of local memory and the lexical environment of the parent. It follows a hierarchical structure, progressing from one parent to the next, establishing the scope chain or Lexical Environment chain.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">a</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">c</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// logic here</span>
  }
  c(); <span class="hljs-comment">// 'c' is lexically inside 'a'</span>
} <span class="hljs-comment">// 'a' is lexically inside the global execution</span>
</code></pre>
<p>The accessibility of variables, functions, and objects is determined by their physical position in the source code, also known as lexical or static scope. It's a hierarchical structure, with the inner encircled by the outer's lexical scope.</p>
<hr />
<h3 id="heading-tldr-understanding-lexical-scope">TLDR: Understanding Lexical Scope</h3>
<p>In simple terms, an inner function can access variables in outer functions, no matter how deeply nested they are. In all other cases, a function cannot access variables outside of its scope.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706368056058/7b4e0abe-538b-4eae-91b0-cd889a2609db.jpeg" alt class="image--center mx-auto" /></p>
<hr />
]]></content:encoded></item><item><title><![CDATA[JavaScript Memory: Figuring out Undefined vs. Not Defined]]></title><description><![CDATA[Introduction: Preparing for JavaScript's Memory dance.
As developers, we frequently find ourselves navigating the complexities of JavaScript, where even little errors can lead to bewilderment. In this digital dance, the first act begins with memory a...]]></description><link>https://blog.siddheshshende.com/javascript-memory-figuring-out-undefined-vs-not-defined</link><guid isPermaLink="true">https://blog.siddheshshende.com/javascript-memory-figuring-out-undefined-vs-not-defined</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[WeMakeDevs]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Siddhesh Shende]]></dc:creator><pubDate>Fri, 26 Jan 2024 07:42:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706254545152/f75d8336-c2d0-4c36-a6b8-b6ab5690ede4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction-preparing-for-javascripts-memory-dance">Introduction: Preparing for JavaScript's Memory dance.</h3>
<p>As developers, we frequently find ourselves navigating the complexities of JavaScript, where even little errors can lead to bewilderment. In this digital dance, the first act begins with memory allocation, which is the process by which JavaScript reserves space for variables and functions. Within this unknown environment, two major players emerge: <mark> Undefined and Not Defined.</mark></p>
<p>In this exploration, we'll delve into the complexities of these concepts, revealing the details that describes JavaScript's memory landscape. From Undefined's placeholder nature to Not Defined's unclear absence, each phrase is critical to the code execution script.</p>
<hr />
<h3 id="heading-memory-allocation-the-beginning-of-the-code-execution">Memory Allocation: The Beginning of the Code Execution.</h3>
<p>JavaScript, the language of dynamic possibilities, does not jump right into code execution. Before any line of code is displayed, a background procedure known as memory allocation takes place. It's similar to laying out the stage for a major performance, with each variable and function allocated the placeholder "Undefined."</p>
<h3 id="heading-undefined-a-placeholder-in-the-memory-area"><strong>Undefined:</strong> A placeholder in the Memory Area.</h3>
<p>The anticipation preceding revelation is undefined in terms of memory allocation. It is the state in which memory is allocated for a variable but no value is assigned to it. It's the beginning of a variable's journey, stating, "I'm here, but I'm waiting."</p>
<p>But what happens if a variable does not appear during the memory allocation phase? This is where Not Defined comes into the forefront.</p>
<h3 id="heading-not-defined-the-puzzle-beyond-memory"><strong>Not Defined:</strong> The Puzzle Beyond Memory.</h3>
<p>Not Defined is more than just a synonym for Undefined; it describes a situation in which an object or variable is not declared or found during memory allocation. If you try to access this mysterious entity, you will be greeted with the harsh message Uncaught Reference Error.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(a); <span class="hljs-comment">// Uncaught ReferenceError: a is not defined</span>
</code></pre>
<p>Here, the variable 'a' isn't simply undefined; it's completely missing from the memory landscape.</p>
<h3 id="heading-decoding-the-differences-undefined-vs-empty-an-important-difference">Decoding the Differences Undefined vs. Empty: An Important Difference</h3>
<p>It is critical to distinguish between undefined and empty. Undefined is not simply a void; it is a keyword with its own reserved memory area. It acts as a placeholder until a variable accepts a specific value.</p>
<p>Examples of Undefined:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 1</span>
<span class="hljs-keyword">var</span> a; <span class="hljs-comment">// Memory is allocated for 'a', but no value is assigned yet</span>
<span class="hljs-built_in">console</span>.log(a); <span class="hljs-comment">// Output: undefined</span>

<span class="hljs-comment">// Example 2</span>
<span class="hljs-keyword">var</span> x;
<span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// Output: undefined</span>

<span class="hljs-comment">// Example 3</span>
<span class="hljs-built_in">console</span>.log(y); <span class="hljs-comment">// Output: ReferenceError: y is not defined</span>
</code></pre>
<h3 id="heading-javascript-is-loosely-typed-language">JavaScript is loosely typed language.</h3>
<p>JavaScript, a flexible language, embraces loose typing. Variables are not restricted to specific data types. Declare 'var a = 5,' then translate it into a boolean or string. It's a playground for flexibility.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Warning: Never manually assign Undefined. Let undefined conduct the JavaScript symphony. Never forcefully assign undefined to a variable; instead, allow it to develop naturally.</div>
</div>

<hr />
<h3 id="heading-conclusion">conclusion...</h3>
<p>Understanding the complexity of undefined vs. not defined in JavaScript is like reading the language's mental state. Memory allocation sets the scene, and these concepts play important roles in the developing drama of code execution. Accept the undefined as a placeholder, and take note of the absence indicated by not defined. JavaScript, with its flexibly typed syntax, thrives on this dynamic interaction. So, let the variables dance while the code unfolds naturally and professionally.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706254090345/35f384d8-0a23-4518-83c5-d18c486bd3e5.jpeg" alt class="image--center mx-auto" /></p>
<hr />
]]></content:encoded></item><item><title><![CDATA[Discovering JavaScript's Hidden Wonders: Mastering the Shortest Programs]]></title><description><![CDATA[Introduction
Embark on a journey into the core of JavaScript, where the seemingly simple programme hides a world of complexity. In this research, we will uncover the mysteries of the smallest JavaScript programme, the formation of the "Window" object...]]></description><link>https://blog.siddheshshende.com/discovering-javascripts-hidden-wonders-mastering-the-shortest-programs</link><guid isPermaLink="true">https://blog.siddheshshende.com/discovering-javascripts-hidden-wonders-mastering-the-shortest-programs</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[WeMakeDevs]]></category><category><![CDATA[Hashnode]]></category><dc:creator><![CDATA[Siddhesh Shende]]></dc:creator><pubDate>Thu, 25 Jan 2024 09:25:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706174517046/4e22f4ef-2eb7-4712-8574-6e404efcb5f2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>Embark on a journey into the core of JavaScript, where the seemingly simple programme hides a world of complexity. In this research, we will uncover the mysteries of the smallest JavaScript programme, the formation of the "Window" object, and the importance of the cryptic "this" keyword.</p>
<hr />
<h3 id="heading-introducing-the-shortest-javascript-programme">Introducing the shortest JavaScript programme.</h3>
<p>The shortest JavaScript programme may surprise you: it is an empty file. Despite the lack of explicit code, the JavaScript engine is hard at work, performing numerous functions behind the scenes.</p>
<h3 id="heading-global-execution-context-setup">Global Execution Context Setup</h3>
<p>When the JavaScript engine encounters an empty file, it commences the establishment of a global execution context. Simultaneously, the global memory component, which stores the variable environment, is created.</p>
<h3 id="heading-role-of-the-global-object-window">Role of the Global Object: "Window"</h3>
<p>In the browser environment, the JavaScript engine creates a global object called "Window." This object stores many functions and variables. One intriguing aspect is that it may be accessed from anywhere in the programme, making it a formidable force.</p>
<h3 id="heading-understanding-the-this-keyword-in-short">Understanding the "this" keyword in short.</h3>
<p>Along with global object generation, the engine creates a critical element: the "this" keyword. This keyword refers to the window object at the global level. To put it simply, the Global Execution Context, global object (window), and "this" variable are created.</p>
<h3 id="heading-global-object-variation-across-javascript-runtimes">Global Object Variation Across JavaScript Runtimes.</h3>
<p>While the name "Window" is common in browsers, it takes on a different meaning in Node.js. Notably, at the global level, the equivalency is valid: this === window.</p>
<h3 id="heading-variable-attachment-to-the-global-object">Variable Attachment to the Global Object</h3>
<p>When we declare a variable in the global scope, we observe an interesting behaviour. Such variables are attached to the global object, creating a direct relationship.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> x = <span class="hljs-number">10</span>;
<span class="hljs-built_in">console</span>.log(x);        <span class="hljs-comment">// 10</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.x);   <span class="hljs-comment">// 10</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">window</span>.x); <span class="hljs-comment">// 10</span>
</code></pre>
<h3 id="heading-extra-knowledge-gyaan-global-and-local-objects">Extra Knowledge (Gyaan): Global and Local Objects</h3>
<p>The global object is a unique and shared entity across all execution contexts in a JavaScript environment, whether it is a browser or Node.js. However, within a function's execution environment, a local object known as the variable object or activation object takes precedence. This localised object contains variables, function parameters, and declarations unique to the function's scope. It is important to note that the activation context (variable object) cannot be accessed directly or explicitly from outside the execution context.</p>
<hr />
<p>Embark on this tour of JavaScript complexities, where even the smallest programme reveals a world of behind-the-scenes processes.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706173543660/4ba63983-b3d8-4dca-bec9-3643810c72b9.jpeg" alt class="image--center mx-auto" /></p>
<hr />
]]></content:encoded></item><item><title><![CDATA[Magic Unleashed: JavaScript Functions & Variables Environment Mastery.]]></title><description><![CDATA[Welcome to the exciting world of JavaScript, where functions and variable environments form the foundation of dynamic web development. In this detailed blog, we'll go on a journey to decode the inner workings of JavaScript functions and investigate t...]]></description><link>https://blog.siddheshshende.com/magic-unleashed-javascript-functions-variables-environment-mastery</link><guid isPermaLink="true">https://blog.siddheshshende.com/magic-unleashed-javascript-functions-variables-environment-mastery</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[WeMakeDevs]]></category><category><![CDATA[Hashnode]]></category><dc:creator><![CDATA[Siddhesh Shende]]></dc:creator><pubDate>Wed, 24 Jan 2024 17:56:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706117579900/7b29350d-6dab-48d8-9d40-c276fff924ff.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to the exciting world of JavaScript, where functions and variable environments form the foundation of dynamic web development. In this detailed blog, we'll go on a journey to decode the inner workings of <mark>JavaScript functions</mark> and investigate the critical role of <mark>variable environments</mark>. Whether you're a seasoned developer or just starting out, grasping these fundamental concepts is critical for creating efficient and strong code.</p>
<hr />
<h2 id="heading-decoding-javascript-functions">Decoding JavaScript functions ❤️</h2>
<p>JavaScript functions are more than simply code snippets; they are dynamic entities that generate their own execution contexts when called. Let's look at the essential elements that make functions in JavaScript truly unique:</p>
<h3 id="heading-1-local-variables-and-functional-scope">1. Local Variables and Functional Scope</h3>
<p>Functions define their area, known as the variable environment or Memory Component. This distinct space enables for the use of local variables that are restricted to the function's limits. These local variables are secret and only accessible within the function unless expressly shared via closures—a topic we'll discuss later.</p>
<h3 id="heading-2variable-hoisting-in-javascript">2.Variable Hoisting in JavaScript</h3>
<p>JavaScript has a unique method called variable hoisting. This approach enables functions to be called before they are defined because variable definitions are relocated to the top of their appropriate scopes during the compilation phase. This ensures that functions can be called effortlessly, hence increasing the flexibility of your code.</p>
<p><strong>The Role of Variable Environment in Execution Context</strong></p>
<h3 id="heading-3memory-component-in-the-execution-context">3.Memory component in the execution context.</h3>
<p>The variable environment, often known as the <strong>memory component</strong>, is where variables and functions reside during runtime. Key items to consider:</p>
<ul>
<li><p>Each execution context has its own variable environment, which guarantees isolation.</p>
</li>
<li><p>When a variable is accessed, JavaScript first looks within the local variable environment before moving on to the outer environments and finally the global variable environment.</p>
<h3 id="heading-4lexical-scoping-for-variable-resolution">4.Lexical Scoping for Variable Resolution.</h3>
<p>  Lexical scoping is made easier by JavaScript's hierarchical variable environment structure. Variables are resolved depending on their closeness to the current execution context, resulting in a reliable and predictable scoping method.</p>
</li>
</ul>
<p><strong>Deep Dive into JavaScript Code Flow</strong></p>
<p>Let's look at a code snippet to visualize the flow of execution context and variable environments:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> x = <span class="hljs-number">1</span>;
a();
b();
<span class="hljs-built_in">console</span>.log(x);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">a</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> x = <span class="hljs-number">10</span>;
  <span class="hljs-built_in">console</span>.log(x);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">b</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> x = <span class="hljs-number">100</span>;
  <span class="hljs-built_in">console</span>.log(x);
}
</code></pre>
<h3 id="heading-5step-by-step-execution">5.Step by Step Execution</h3>
<ul>
<li><p>The Global Execution Context (GEC) is constructed, and 'x' is initialised to 1.</p>
</li>
<li><p>Function a() is called, which generates a new execution context. Local 'x' within a() is set to ten, and console.log(x) returns 10.</p>
</li>
<li><p>After executing a(), the context is removed from the call stack and returned to GEC.</p>
</li>
<li><p>The function b() is invoked to create a new context. Local 'x' in b() is set to 100, and console.log(x) returns 100.</p>
</li>
<li><p>After executing b(), the context is removed from the call stack and returned to GEC.</p>
</li>
<li><p>Console.log(x) in the global scope returns the global 'x' value of 1.</p>
</li>
</ul>
<h3 id="heading-6code-flow-visualization">6.Code Flow Visualization</h3>
<p>As we unravel the mystery, visualize the code flow, demonstrating the delicate dance between functions and variable contexts in the JavaScript world.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706118707663/cc30e17a-d733-43f0-9d06-32cc7b23e455.jpeg" alt class="image--center mx-auto" /></p>
<hr />
<h3 id="heading-conclusion-harness-the-power-of-javascript-functions-and-environments">Conclusion: Harness the Power of JavaScript Functions and Environments</h3>
<p>Finally, this guide will help you navigate the ever-changing terrain of JavaScript functions and variable environments. With this understanding, you'll be better able to write code that is both functional and elegant. As you progress through your coding journey, continue to explore the depths of JavaScript in order to master the art of web development.</p>
<p>Stay Tuned!! Happy Learning!!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706116992306/3bc2eadc-59a9-468f-8e1c-6cf841694ab0.jpeg" alt class="image--center mx-auto" /></p>
<hr />
]]></content:encoded></item></channel></rss>