<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by SR Sajjad on Medium]]></title>
        <description><![CDATA[Stories by SR Sajjad on Medium]]></description>
        <link>https://medium.com/@srsajjad?source=rss-d2597ff64449------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EYqWAGgXuZbj9M7-3BvQ8w.jpeg</url>
            <title>Stories by SR Sajjad on Medium</title>
            <link>https://medium.com/@srsajjad?source=rss-d2597ff64449------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 18:49:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@srsajjad/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Optimizing Loop In JavaScript]]></title>
            <link>https://medium.com/swlh/optimizing-loop-in-javascript-6f39c9eae633?source=rss-d2597ff64449------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f39c9eae633</guid>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <dc:creator><![CDATA[SR Sajjad]]></dc:creator>
            <pubDate>Thu, 16 Apr 2020 09:28:57 GMT</pubDate>
            <atom:updated>2024-06-24T13:08:00.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8Qrw4ZqDZdICKMTb" /><figcaption>Photo by <a href="https://unsplash.com/@shortworkphotography?utm_source=medium&amp;utm_medium=referral">Jay Short</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you’ve been writing code for a while you might’ve developed a level of empathy for your machine. “It shouldn’t work much while running my code”. Not speaking of hard core algorithm optimization. But yah, it surely feels bad when there’s a loop inside another loop.</p><p>While writing JavaScript, there are many places we could optimize our code to run faster.<br>Like -</p><ul><li>take the hot code out of main thread</li><li>make async calls parallel with Promise.all</li><li>debounce or throttle certain functions</li><li>use CSS properties that will trigger less rendering cycles</li></ul><p>…and such points go on.</p><p>One most obvious thing among them is Loop. Loops are scary.</p><p>But maybe in most cases, the loop isn’t the reason for bad performance but you might want to avoid unnecessary iterations. Hence the blog post people !</p><blockquote><em>The target is actually any kind of repetition like — loop, recursion or whatever</em></blockquote><p>In JavaScript there are many APIs to write loop. These days we mostly use map, reduce, filter, forEach. It feels really good to write them. Because they enforce functional approach and the code management is good too.</p><p>Let’s jump to the points — how we can write better Loops.</p><p><strong>The Magic Words — </strong><strong>break , </strong><strong>continue and </strong><strong>return</strong></p><pre>for(let i = 0; i &lt; arr.length; i++){<br><br>    // we have got our answer <br>    break<br><br>    // we don&#39;t need to go further in this iteration<br>    continue<br><br>    // heavy calculation here<br>}</pre><p>Do you see what’s happening here ? Now in forEach, map, filter - they don&#39;t stop. They are going to run through all iterations until the last index. Break doesn&#39;t work.</p><p>So in such cases we should pick for loop instead of trying to be cool. While the classic for loop is perfectly fine, you might want to use a better looking API - for of.</p><pre>for (let val of arr){<br><br>    // we have got our answer <br>    break<br><br>    // we don&#39;t need to go further in this iteration<br>    continue<br><br>    // heavy calculation here<br>}</pre><p>Now the gotcha is — what if we need index inside this loop ? In for of there&#39;s no direct index support. But there&#39;s always a hack for almost everything.</p><pre>for (let [index, val] of Object.entries(arr)){<br><br>}</pre><p>If the loop is inside a function, and we use return inside that loop, the whole function is going to return.</p><pre>function doSomething(){<br><br>  for(let val of arr){<br><br>    // mission accomplished<br>    return<br><br>    // some heavy calculation going on here<br>  }<br><br>}</pre><p>This can’t be done in forEach, map or some other array looping functional method. Because they have their own return.</p><p><strong>You Might Not Need Iteration</strong></p><p>Let’s look at another example -</p><pre>let playerInfo = [<br>    {<br>        name: &#39;Messi&#39;,<br>        club: &#39;Barcelona&#39;<br>    },<br><br>    {<br>        name: &#39;Ronaldo&#39;,<br>        club: &#39;Juventus&#39;<br>    },<br><br>    {<br>        name: &#39;Neymar&#39;,<br>        club: &#39;PSG&#39;<br>    }<br>]<br><br>// here we want to find Neymar&#39;s club from this array</pre><pre>let club = playerInfo.find(player =&gt; player.name === &#39;Neymar&#39;).club)</pre><pre>console.log(club)</pre><p>For this, we need to loop over each element and check if it’s Neymar and then get the club’s value.</p><p>Sometimes a hashing/ dictionary approach would be better. Because then we don’t need to iterate again and again. Just access the value directly.</p><pre>const playerInfo = {<br>  Messi: &#39;Barcelona&#39;,<br>  Ronaldo: &#39;Juventus&#39;,<br>  Neymar: &#39;PSG&#39;<br>}<br><br>console.log(playerInfo.Neymar)</pre><p>Maybe it’s not the best example, but I am pretty sure you’d find better use case for this approach.</p><p>In some cases, this kind of object approach can save you from O(N^2) complexity.</p><pre>// let&#39;s find out if there&#39;s any repetition in this array<br>let arr = [1, 2, 3, 1] // 1 appears twice, so there&#39;s repetition<br><br>// loop on every item<br>// on another inner loop check -<br>// if this item has appeared in any other index</pre><pre>// so that would be O(N^2) solution<br><br><br>// Or,<br>// hash the value on one loop</pre><pre>let obj = {}<br>arr.forEach((v,i) =&gt; obj[v] ? obj[v]++ : obj[v] = 1)<br><br>// and on another loop check if the hash object has some key<br>// containing value greater than 1</pre><pre>// that would be of O(N+N) complexity and that&#39;s better</pre><p>For some cases, you might consider a math equation instead of loop. Like — find out the summation of an explicit sequence.</p><pre>let arr = [1, 2, 3, 4, 5]<br><br>// which is better in this case ?<br><br>// this ?<br>let total = arr.reduce((currentVal, reducedVal) =&gt; currentVal + reducedVal , 0)<br><br>// or this ?<br>let n = 5 // last element - arr[arr.length - 1]<br>let sum = (n * (n+1)) / 2<br><br><br>// another dumb example<br>// which is better here ?</pre><pre>let arr = [2, 2, 2, 2, 2, 2]<br><br>// this ?<br>let total = eval(arr.join(&#39;+&#39;)) // eval ? really ??<br><br>// or this ?<br>let sum = 2 * arr.length</pre><p><strong>Use the Correct Array Method for Particular Scenario</strong></p><p>There are varieties of built in array methods available in JavaScript. Some are similar but each one has it’s own purpose. It’s better to think twice before applying map or filter for all use cases.</p><p>For example — find vs filter</p><p>find is a better suit if we are looking for only one item. And find stops iterating after the desired value is found. filter would iterate until the last index as it&#39;s looking for all the matches.</p><p>There are other same <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">cases</a>.</p><p><strong>Memoization</strong></p><p>Sometimes there could be same function calls with same parameters, in those cases we can save the value on first execution. Instead of running the function again, we could just use that saved value. This process is called memoization.</p><p>Just to give a rough idea — a silly example — look for better examples on the internet.</p><pre>let cache = {}<br>​<br>function plus(x){<br>  // there might be heavy calculation here<br>  console.log(&#39;i am here&#39;) // LOL<br>  return x + 2<br>}<br>​<br>function memoizedPlus(a){<br>  if(cache[a]){<br>    return cache[a]<br>  }<br><br>  else{<br>    cache[a] = plus(a)<br>    return cache[a]<br>  }<br>}</pre><pre>// run this code in your console and see what happens​</pre><pre>console.log(memoizedPlus(5))<br>console.log(memoizedPlus(1))<br>console.log(memoizedPlus(5))<br>console.log(memoizedPlus(3))<br>console.log(memoizedPlus(3))</pre><p>I had a plan to talk about handling async operation inside loop. Maybe in another article. So for now that’s all folks ! Stay safe and have fun.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*7RMw-ff98-J6I3x1.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f39c9eae633" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/optimizing-loop-in-javascript-6f39c9eae633">Optimizing Loop In JavaScript</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Sneak Peek At Asynchronous JavaScript]]></title>
            <link>https://medium.com/@srsajjad/a-sneak-peek-at-asynchronous-javascript-e56dca938ba?source=rss-d2597ff64449------2</link>
            <guid isPermaLink="false">https://medium.com/p/e56dca938ba</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[SR Sajjad]]></dc:creator>
            <pubDate>Fri, 31 Jan 2020 06:47:31 GMT</pubDate>
            <atom:updated>2024-06-24T13:06:22.729Z</atom:updated>
            <content:encoded><![CDATA[<p>The word <strong>Asynchronous</strong> means - something will happen in the future without blocking other tasks.</p><p>Let’s say we wrote some instructions with JavaScript.</p><pre>A. do this<br>B. do this<br>C. do this</pre><p>A will be executed<br>then B<br>then C</p><p>Serially. Common Sense, right ?<br>But sometimes, it’s not the case. Let’s see -</p><pre>let name = &quot;Heisenberg&quot;</pre><p>This variable name has a <strong>value</strong>. You want to print out this value.</p><pre>console.log(name)</pre><p>What if this <strong>value</strong> isn’t available in your code. It’s somewhere else outside . Maybe some server serves this <strong>value</strong> when we send HTTP request.<br>Or maybe it’s inside a file.</p><p>So it’s not in your code right now. Your program will have to fetch it from outside.</p><p>Now the code looks like this -</p><pre>let name;</pre><pre>// hitting an imaginary service sending a String value as response</pre><pre>fetch(&quot;/saymyname&quot;)<br>  .then( res =&gt; res.text() )<br>  .then( value =&gt; name = value )</pre><pre>console.log(name)</pre><p>There’s a bug in the code. The output would be - undefined .</p><p>name variable’s <strong>value</strong> is still undefined as it was initialized. It wasn’t overridden as we wanted to do inside the fetch code.</p><p>That’s because JavaScript skips this fetching operation and continues executing the following lines of your code.</p><p>This fetching happens in the background by the Operating System and we get a Promise in our code that, when the resolved value will be available, we can use that data. And that’s why we’ll have to move our printing operation there too</p><pre>let name;</pre><pre>fetch(&quot;/saymyname&quot;)<br>  .then( res =&gt; res.text() )<br>  .then( value =&gt; {<br>     name = value<br>     console.log(name)<br>   })</pre><p>We’ve just used some <strong>Async</strong> code.</p><p>Normally JavaScript is Synchronous. But there are some specific APIs in the language which are Asynchronous by nature. Like here we’ve used fetch API.</p><p>It’s a good thing because otherwise this program would freeze until the data is available for us.</p><p>But this is also problematic because it’s not a regular way of writing code, there’s an overhead of keeping async things in the sync. For this, we have a much cleaner API now — async/await. Which also blocks, but you get to control where and when you want to block.</p><p>Another thing we want to take advantage of is — Parallel Execution (Concurrent precisely). In our previous example, if we had multiple fetching operations, they would happen in parallel. Thanks to the multi threading interface of Operating System.</p><p>To understand this let’s look at another example. Say we want to read text from 2 different files.</p><pre>async function readFiles() {<br>  let text1 = await readFile(&#39;/fileOne.txt&#39;) // 3 seconds<br>  console.log(&quot;text from file one&quot;, text)<br><br>  let text2 = await readFile(&#39;/fileTwo.text&#39;) // 2 seconds<br>  console.log(&quot;text from file two&quot;, text)<br>}<br><br>readFiles()<br><br>console.log(&quot;Processing...&quot;)</pre><p>This looks nice, but this is blocking code. They are independent operations and should take only 3 seconds to process. But now they are taking 3 + 2 = 5 seconds.</p><p>So how to write this in parallel ?</p><p><strong>Promise.all()</strong> — this API handles multiple independent Async operations in paralllel. And we can await for the whole process to finish.</p><pre>const [text1, text2] = await Promise.all([<br>                          readFile(&#39;/fileOne.txt&#39;),<br>                          readFile(&#39;/fileTwo.txt&#39;)<br>                        ])</pre><pre>console.log(&quot;Done&quot;)</pre><p>Here, both file reading operations are parallel and also we get resolved values in sequence. This is great.</p><p>Except, this API short circuits. If any of these operations fails, the whole thing fails from that point. What if we want it to work as <strong>Microservice</strong>, meaning — an Async operation can fail, but we still want other operations’ resolved values, then we can’t use Promise.all(). Instead we need to use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled"><strong>Promise.allSettled()</strong></a>.</p><p>So now, we have this basic idea that there can be different requirements for Async operations and for handling them, there are different variances of Promise API too. Like another useful one is <strong>Promise.race()</strong>.</p><p><strong>Event Loop</strong></p><p>A promise can have 2 states. <strong>Pending</strong> and <strong>Resolved</strong>/Rejected.</p><p>A pending promise means — it’s being handled in the background.<br>A resolved promise means — it will be executed at the end of the running event loop.</p><p>On each iteration of event loop, we can consider 3 cases -</p><ol><li>If it’s a synchronous code, execute it.</li><li>If it’s a pending Promise then skip it. It’s running in the background.</li><li>If it’s a resolved(rejected) Promise, then this code will run at the end of this particular iteration of event loop.</li></ol><p>When the resolved Promise is available, it’s then-able. Meaning — we can attach a callback to work with the resolved data. <strong>So a resolved Promise can be available anytime inside a particular iteration of</strong> <strong>Event Loop</strong>. And the callback will be fired within this same iteration, but at the very end after finishing all the Synchronous works.</p><p>Let’s look at an interesting case -</p><pre>setTimeout(()=&gt; console.log(&#39;timeout&#39;), 0)</pre><pre>Promise.resolve().then(()=&gt; console.log(&#39;resolved promise&#39;))</pre><pre>console.log(&#39;synchronous&#39;)</pre><p>We are emulating a resolved Promise here and also a timer. So on a running event loop phase, after finishing all the Sync code, it’s going to check</p><ul><li>If there’s any callback of resolved Promise to run.</li><li>If there’s a timer callback to run.</li></ul><p>So before the timer callback, it’s going to check if there’s any resolved promise. First they are going to be executed. It doesn’t matter how much time it takes, and in the mean time, there could be other resolved promises popped up in the current event loop. After finishing all of them, then the timer callback gets executed finally.</p><p>That means, you can’t expect the timer to run, after the exact interval you provided, like here we did- 0 ms. It might take longer than that.</p><p>So output of the code —</p><pre>synchronous<br>resolved promise<br>timeout</pre><p><strong>N.B</strong>. Different browsers can have different implementations. This is Chrome/Node standard behavior.</p><p>To understand how event loop actually works- read this- <a href="https://nodejs.org/uk/docs/guides/event-loop-timers-and-nexttick/">https://nodejs.org/uk/docs/guides/event-loop-timers-and-nexttick/</a></p><p>And a fantastic article by Jake Archibald on Task, Microtask scheduing -<br><a href="https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/">https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/</a></p><p>That’s all folks. Have fun with your Asynchronous journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e56dca938ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Read File With Response API]]></title>
            <link>https://medium.com/@srsajjad/read-file-with-response-api-fa3e0f735c29?source=rss-d2597ff64449------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa3e0f735c29</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[SR Sajjad]]></dc:creator>
            <pubDate>Tue, 18 Dec 2018 06:11:09 GMT</pubDate>
            <atom:updated>2020-02-01T12:34:24.044Z</atom:updated>
            <content:encoded><![CDATA[<p>How can we read file from the browser ?</p><p>Say, we want to read a text file. We can just use <strong>File Reader API</strong> to do that. So the code will be like this.</p><pre>let fileReader = new FileReader()<br>let fileInput = document.querySelector(&#39;input&#39;)</pre><pre>fileInput.addEventListener(&#39;change&#39;, handleFile)</pre><pre>function handleFile (e) {<br>  let file = e.target.files[0]</pre><pre>  fileReader.onload = function (event) {<br>    let text = event.target.result<br>    console.log(&#39;text&#39;, text)<br>  }</pre><pre>  fileReader.readAsText(file)<br>}</pre><p>When I first saw this code, it looked so weird !</p><p>Now lets look at how we could use <strong>Response API</strong> to do the same.</p><pre>const handleFile = async e =&gt; {<br>  let file = e.target.files[0]<br>  let res = new Response(file)<br>  let text = await res.text()<br>  console.log(&#39;text&#39;, text)<br>}</pre><pre>let fileInput = document.querySelector(&#39;input&#39;)<br>fileInput.addEventListener(&#39;change&#39;, handleFile)</pre><p>Now this looks much more intuitive. Doesn’t it ?</p><p>We could turn the repsonse into anything like <strong>blob/arrayBuffer/text/json/formData</strong></p><pre>let blob = await res.blob()</pre><pre>let buffer = await res.arrayBuffer()</pre><pre>let json = await res.json()</pre><pre>let formData = await res.formData()</pre><p>Nice !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa3e0f735c29" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>