<?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 Aman Kalra on Medium]]></title>
        <description><![CDATA[Stories by Aman Kalra on Medium]]></description>
        <link>https://medium.com/@aman-kalra4?source=rss-5048408cc855------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Rzg1yQUwlvk6KT0oxdRyzw.jpeg</url>
            <title>Stories by Aman Kalra on Medium</title>
            <link>https://medium.com/@aman-kalra4?source=rss-5048408cc855------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:44:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aman-kalra4/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[Code Splitting in React: Not Just Another Buzzword ]]></title>
            <link>https://medium.com/walmartglobaltech/code-splitting-in-react-not-just-another-buzzword-6ec266000b71?source=rss-5048408cc855------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ec266000b71</guid>
            <category><![CDATA[react-code-splitting]]></category>
            <category><![CDATA[dynamic-loading]]></category>
            <category><![CDATA[react-suspense]]></category>
            <category><![CDATA[code-splitting]]></category>
            <category><![CDATA[react-lazy-loading]]></category>
            <dc:creator><![CDATA[Aman Kalra]]></dc:creator>
            <pubDate>Tue, 09 Sep 2025 13:41:30 GMT</pubDate>
            <atom:updated>2025-09-09T13:41:30.179Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xWMRZTpgNbDg1CzS7p8AKQ.png" /></figure><p>Modern web apps are getting larger and complex every day. As developers, our mission is to deliver fast, responsive experiences to users without bloating their browsers. And, React offers us tools like <strong>React.lazy</strong> and <strong>Suspense</strong> to help us split our bundles and load code on demand. In this article, we’ll dive deep into how these features work, how they reduce bundle size, and how they make your app faster and more efficient.</p><h3>🔍 The Problem: Big Bundles = Slow Apps</h3><p>When you build a React app, all of your JavaScript typically ends up in one or more large bundles, leading to:</p><ul><li>📦 Large bundle size</li><li>🐢 Longer initial load time</li><li>📉 Poor performance on slow networks</li><li>🧠 High client‑side memory usage</li><li>📉 Lower Core Web Vitals</li></ul><p><strong>Solution:</strong> <em>Code‑splitting</em> — breaking your code into smaller chunks and loading them only when needed.</p><h3>⚡ React.lazy &amp; Suspense to the Rescue</h3><h4><strong>React.lazy</strong></h4><p><strong>React.lazy</strong> lets you import a component <strong>only when it&#39;s needed</strong>. This is known as <strong>dynamic import</strong> or <strong>lazy loading</strong>. It enables the application to defer the loading of non-critical components until they are required, improving the initial load time of the application.</p><p>Internally, it leverages the native JavaScript <strong>import()</strong> function and allows you to treat dynamically loaded components as if they were regular ones.</p><pre>const SomeComponent = React.lazy(() =&gt; import(&#39;./ComponentPath&#39;));</pre><p>This tells React to split this component into a separate chunk and load it <strong>only when it is actually rendered.</strong></p><h4><strong>React.Suspense</strong></h4><p><strong>React.Suspense</strong> is a built in React component designed to handle the asynchronous nature of components loaded via <strong>React.lazy</strong>.</p><p>Since a lazy component doesn’t immediately return a rendered result, <strong>Suspense</strong> provides a graceful fallback UI during that loading period.</p><p>The fallback can be any UI element of your choice like — a <strong>loading indicator,</strong> <strong>skeleton</strong> <strong>placeholder</strong>, or even a <strong>custom animation</strong> — shown while the lazy-loaded component is rendered.</p><pre>&lt;Suspense fallback={&lt;FallbackComponent /&gt;}&gt;<br> &lt;LazyComponent /&gt;<br>&lt;/Suspense&gt;</pre><p>The <strong>fallback</strong> prop is what will be displayed while the lazy component is still loading.</p><p>Now let’s bring above concepts together in a working example:</p><pre>import React, { Suspense } from &#39;react&#39;;<br>import { BrowserRouter as Router, Route, Routes } from &#39;react-router-dom&#39;;<br>import Home from &#39;./Home&#39;;<br><br>const NotificationsDashboard = React.lazy(() =&gt; import(&#39;./NotificationsDashboard&#39;));<br>const TabularView = React.lazy(() =&gt; import(&#39;./TabularView&#39;));<br><br>function App() {<br>  return (<br>    &lt;Router&gt;<br>      &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>        &lt;Routes&gt;<br>          &lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt;<br>          &lt;Route path=&quot;/notifications&quot; element={&lt;NotificationsDashboard /&gt;} /&gt;<br>          &lt;Route path=&quot;/tabular-view&quot; element={&lt;TabularView /&gt;} /&gt;<br>        &lt;/Routes&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/Router&gt;<br>  );<br>}</pre><p>Instead of loading all route components upfront, the above code loads only the <strong>Home</strong> route immediately, while the <strong>/notifications</strong> and <strong>/tabular-view</strong> components are lazy-loaded on demand.</p><p>But this doesn’t mean you should lazy load every component. While lazy loading helps reduce the initial bundle size, it also introduces additional network requests and slight delays as the browser fetches and parses the split JavaScript files. For small, frequently used, or above-the-fold (i.e. visible when the page initially loads) UI elements — such as headers, navigation bars, buttons, or form inputs, lazy loading them can actually degrade performance by deferring the rendering of critical content unnecessarily.</p><p>Instead, reserve lazy loading for components that:</p><ul><li>Are not visible on the initial screen (e.g., modals, dashboards, or settings pages)</li><li>Contain heavy logic or large third-party libraries</li><li>Are route-specific and rarely visited by every user</li></ul><p>Striking the right balance between eagerly and lazily loaded components is key to optimizing both performance and user experience.</p><h3>🎯 Benefits</h3><p>While lazy loading should be done only when requried, but below are the benefits that we can get:</p><p>✅ Reduced initial bundle size</p><p>✅ Faster load times for first-time users</p><p>✅ Better Time-to-Interactive (TTI)</p><p>✅ Efficient memory usage</p><p>✅ On-demand code execution</p><h3>📂 Modular Architecture</h3><p>To further leverage lazy loading, structure your project in a modular way — feature-based folders, lazy-loaded micro-frontends, and dynamically imported utilities. This ensures better maintainability and control over performance bottlenecks.</p><blockquote>⚙️ <strong>Note:</strong> There are various bundlers available like Webpack, Rollup, Parcel, etc. In this article, I assume you’re using <strong>Webpack</strong> for your application setup. Some examples (like chunk naming or bundle visualization) are specific to Webpack’s behavior and tooling.</blockquote><h3>📦 How to View Bundle &amp; its Chunk Files</h3><h4>🛠️ Build the App</h4><p>Assuming you have Webpack set up with the appropriate configuration files, here’s a basic example of how your setup might look:</p><p><strong>webpack.common.js</strong> (partial code):</p><pre>module.exports = {<br>  output: {<br>    filename: &#39;[name].js&#39;,<br>    path: path.resolve(__dirname, &#39;build&#39;),<br>    clean: true,<br>  },<br>};</pre><p><strong>webpack.prod.js</strong> (partial code):</p><pre>const { merge } = require(&#39;webpack-merge&#39;);<br>const common = require(&#39;./webpack.common&#39;);<br><br>module.exports = merge(common, {<br>  mode: &#39;production&#39;,<br>});</pre><p>Then run the following command to generate your production build:</p><pre>npx webpack --config webpack.prod.js</pre><p>This will create a <strong>build/</strong> folder in the root directory of your project, where you can inspect the generated chunk files, including your lazy-loaded components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*tAHB7F0xNOZLpdv2SdmU9A.png" /><figcaption>build folder generated after running mentioned command</figcaption></figure><h4>🛠️ Check the Build Output</h4><p>Webpack allows naming your dynamically imported chunks.</p><p>This naming helps:</p><ul><li>To debug easily with the help of meaningful file names.</li><li>To track performance issues related to specific components.</li><li>To make lazy loaded components easier to trace in DevTools.</li></ul><pre>const NotificationsDashboard = React.lazy(() =&gt; import(/* webpackChunkName: &quot;NotificationsDashboard&quot; */&#39;./NotificationsDashboard&#39;));<br>const TabularView = React.lazy(() =&gt; import(&#39;./TabularView&#39;));</pre><p>In example discussed above, we lazy loaded 2 components — <strong>NotificationsDashboard</strong> and <strong>TabularView</strong>. After using the named chunk comment in the import statement for <strong>NotificationsDashboard</strong>, you&#39;ll get a file in your build output named something like <strong>NotificationsDashboard.js.</strong> Meanwhile, if you don&#39;t provide a name (as in the case of <strong>TabularView</strong>), webpack will generate a generic file name <strong>like</strong> <strong>363.js</strong> which comes from the naming convention assigned in the webpack config file =&gt; <strong>[name].js</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*StvSVrgF1FhO16BkZ9TkoA.png" /><figcaption>Chunks generated in build folder</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*auPU3v29uWDMGlbUIdDPoA.png" /><figcaption>Lazy Loaded Chunks generated as mentioned in code example</figcaption></figure><h4>🔍 Inspect with Source Maps &amp; Chunk Names</h4><p>Once you’ve built your app, you can verify lazy loading behavior in the browser using Chrome DevTools:</p><ol><li>Run the application</li><li>Open Chrome DevTools → Network tab</li><li>Reload the app</li><li>Filter by <strong>.js</strong> to view JavaScript chunk loads</li></ol><p>You’ll observe files like:</p><ul><li><strong>NotificationsDashboard.js</strong> – named via webpack’s <strong>webpackChunkName</strong> comment.</li><li><strong>src_Pages_TabularView_TabularView_js.js</strong> – unnamed and auto-generated by the bundler.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5rI_oYbyuRAyZysTfZvEJQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_c2jSvFKCb5dsroB1nfNyg.png" /><figcaption>On Demand Loading of Lazy Loaded Routes</figcaption></figure><p>The first time a user navigates to a lazily loaded route or component, the browser makes a network request to fetch the corresponding JavaScript chunk.</p><p>But on subsequent visits to the same route:</p><ul><li>No new network request is made</li><li>The chunk is served directly from the browser’s cache</li></ul><p>This significantly reduces unnecessary re-fetching and improves perceived performance for returning users.</p><p>Since not all components are loaded up front, your <strong>initial bundle size</strong> is smaller.</p><blockquote><strong>Tip:</strong> You can use a bundle analyzer plugin (e.g. <strong>webpack-bundle-analyzer</strong>) to visualize chunk sizes.</blockquote><h4>🌍 Bonus: Beyond JavaScript</h4><h4>🖼️ Lazy Loading Images</h4><p>Images that appear <strong>below-the-fold</strong> (i.e. not visible when the page initially loads) should be lazy-loaded. This reduces the number of resources fetched upfront, improving load times and reducing bandwidth consumption, especially important for users on slower connections or mobile devices.</p><pre>&lt;img loading=&quot;lazy&quot; src=&quot;/images/someBanner.jpg&quot; alt=&quot;Banner&quot; /&gt;</pre><h4>⛓️ External Scripts</h4><p>To optimize how scripts load and execute in your application, use the <strong>async</strong> or <strong>defer</strong> attributes on <strong>&lt;script&gt;</strong> tags:</p><ul><li><strong>async</strong>: Downloads the script asynchronously and executes it <strong>as soon as it’s available</strong>. This can block HTML parsing if the script executes before the DOM is ready, so you can use it mainly for third-party scripts that don’t manipulate the DOM.</li><li><strong>defer</strong>: Downloads the script in parallel but defers its execution until <strong>after the HTML document has been fully parsed</strong>. This is ideal for scripts that need access to the DOM but shouldn’t block rendering.</li></ul><pre>&lt;script defer src=&quot;./scripts/app.js&quot;&gt;&lt;/script&gt;<br><br>&lt;script async src=&quot;https://www.website.com/thirdParty.js&quot;&gt;&lt;/script&gt;</pre><h3>🧪 Hands-On Practice</h3><p>Try picking up one heavy component in your app, lazy‑load it, and measure your bundle reduction. Share your before/after stats in the comments!</p><h3>🚀 Final Thoughts</h3><p>React’s <strong>Suspense</strong> and <strong>lazy</strong> are powerful tools that give you control over what the browser loads and when. By embracing <strong>code splitting</strong>, you&#39;re ensuring that users only download what they need, making your apps faster, more efficient, and more enjoyable to use.</p><p>💬 <em>Have feedback, questions, or tips of your own? Drop them in the comments or reach out on </em><a href="https://www.linkedin.com/in/amankalra1/"><strong><em>LinkedIn</em></strong></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ec266000b71" width="1" height="1" alt=""><hr><p><a href="https://medium.com/walmartglobaltech/code-splitting-in-react-not-just-another-buzzword-6ec266000b71">Code Splitting in React: Not Just Another Buzzword 🚀</a> was originally published in <a href="https://medium.com/walmartglobaltech">Walmart Global Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Polyfills: Code Snippets for Interviews]]></title>
            <link>https://aman-kalra4.medium.com/javascript-polyfills-code-snippets-for-interviews-bf3b67e9d951?source=rss-5048408cc855------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf3b67e9d951</guid>
            <category><![CDATA[javascript-interview]]></category>
            <category><![CDATA[polyfill-in-javascript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[polyfill]]></category>
            <dc:creator><![CDATA[Aman Kalra]]></dc:creator>
            <pubDate>Wed, 08 Jan 2025 14:13:14 GMT</pubDate>
            <atom:updated>2025-05-12T15:04:58.726Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aqzsxF7RaWOxYFS3NmT87Q.jpeg" /></figure><p>JavaScript is an essential skill for frontend developers, and during interviews, questions about creating polyfills often arise. Polyfills demonstrate your understanding of core JavaScript concepts and your ability to write foundational code.</p><p>In this article, I’ll guide you through implementing polyfills for some of the most commonly asked JavaScript methods. These include:</p><ul><li><strong>Array Prototype Methods</strong>: map(), filter(), reduce()</li><li><strong>Function Prototype Methods</strong>: call(), apply(), bind()</li><li><strong>Promise Static Methods: </strong>all()<strong>,</strong> allSettled(), any(), race()</li></ul><h3>Array Prototype Methods</h3><ol><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map() method</a>:</li></ol><p>This method returns a new array by applying a given function to each element in the original array, without mutating it. It’s ideal for transforming data.</p><pre><br>Array.prototype.myMap = function (callbackFn, thisArg) {<br>  const arr = this;<br>  const res = [];<br>  for (let i = 0; i &lt; arr.length; i++) {<br>    res[i] = callbackFn.call(thisArg, arr[i], i, arr);<br>  }<br>  return res;<br>};</pre><p>2. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter">filter() method</a>:</p><p>This method returns a new array containing all elements that pass the test implemented by the provided function, leaving out the others. It’s ideal for filtering data.</p><pre>Array.prototype.myFilter = function (callbackFn, thisArg) {<br>  const arr = this;<br>  const res= [];<br>  for (let i = 0; i &lt; arr.length; i++) {<br>    if (callbackFn.call(thisArg, arr[i], i, arr)) {<br>      res.push(arr[i]);<br>    }<br>  }<br>  return res;<br>};</pre><p>3. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce">reduce() method</a>:</p><p>This method executes a function on each element of the array, resulting in a single output value, often used for aggregation or accumulation.</p><pre>Array.prototype.myReduce = function (callbackFn, initialValue) {<br>    const arr = this;<br>    let accumulator;<br>    let startIndex;<br><br>    if (initialValue !== undefined) {<br>        accumulator = initialValue;<br>        startIndex = 0;<br>    } else {<br>        if (arr.length === 0) {<br>            throw new TypeError(&quot;Reduce of an empty array with no initial value&quot;);<br>        }<br>        accumulator = arr[0];<br>        startIndex = 1;<br>    }<br><br>    for (let i = startIndex; i &lt; arr.length; i++) {<br>        accumulator = callbackFn(accumulator, arr[i], i, arr);<br>    }<br>    return accumulator;<br>};</pre><h3>Function Prototype Methods</h3><ol><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call">call() method</a>:</li></ol><p>This method invokes a function with a specified <strong>this</strong> context and arguments provided individually.</p><pre>Function.prototype.myCall = function (thisArg, ...argArray) {<br>  const func = this;<br>  return func.apply(thisArg, [...argArray]); // using apply()<br>  // return func.bind(thisArg)(...argArray); using bind()<br>};</pre><p>2. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">apply() method</a>:</p><p>This method is similar to <strong>call()</strong>, but accepts arguments as an array.</p><pre>Function.prototype.myApply = function (thisArg, argArray = []) {<br>  const func = this;<br>  return func.call(thisArg, ...argArray); // using call()<br>  // return func.bind(thisArg)(...argArray); using bind()<br>};</pre><p>3. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">bind() method</a>:</p><p>This method returns a new function with a specified <strong>this</strong> value and pre-set arguments, allowing for function reuse with a specific context.</p><pre>Function.prototype.myBind = function (thisArg, ...args1) {<br>  const func = this;<br>  return function(...args2) {<br>    return func.call(thisArg, ...args1, ...args2)<br>  }<br>};</pre><h3>Promise Static Methods</h3><ol><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all">all() method</a>:</li></ol><p>This method waits for all promises in the iterable to resolve, returning a new promise with an array of their results, or rejects if any promise is rejected.</p><pre>Promise.all = function (iterable) {<br>  return new Promise((resolve, reject) =&gt; {<br>    const results = new Array(iterable.length);<br>    let resolved = 0;<br><br>    if (iterable.length === 0) {<br>      resolve(results);<br>      return;<br>    }<br><br>    iterable.forEach((item, index) =&gt; {<br>      Promise.resolve(item)<br>        .then((value) =&gt; {<br>          results[index] = value;<br>          resolved++;<br><br>          if (resolved === iterable.length) {<br>            resolve(results);<br>          }<br>        })<br>        .catch((reason) =&gt; {<br>          reject(reason);<br>        });<br>    });<br>  });<br>};</pre><p>2. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled">allSettled() method</a>:</p><p>This method waits for all promises to settle (either resolved or rejected) and returns an array of their results.</p><pre>Promise.allSettled = function (iterable) {<br>  return new Promise((resolve) =&gt; {<br>    const results = new Array(iterable.length);<br>    let resolved = 0;<br><br>    if (iterable.length === 0) {<br>      resolve(results);<br>      return;<br>    }<br><br>    iterable.forEach((item, index) =&gt; {<br>      Promise.resolve(item)<br>        .then((value) =&gt; {<br>          results[index] = {<br>            status: &quot;fulfilled&quot;,<br>            value,<br>          };<br>        })<br>        .catch((reason) =&gt; {<br>          results[index] = {<br>            status: &quot;rejected&quot;,<br>            reason,<br>          };<br>        })<br>        .finally(() =&gt; {<br>          resolved++;<br>          if (resolved === iterable.length) {<br>            resolve(results);<br>          }<br>        });<br>    });<br>  });<br>};</pre><p>3. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/any">any() method</a>:</p><p>This method returns a promise that resolves as soon as any promise in the iterable resolves, or rejects if all promises are rejected.</p><pre>Promise.any = function (iterable) {<br>  return new Promise((resolve, reject) =&gt; {<br>    const errors = [];<br>    let rejected = 0;<br><br>    if (iterable.length === 0) {<br>      return reject(new AggregateError([], &quot;All promises were rejected&quot;));<br>    }<br><br>    iterable.forEach((item, index) =&gt; {<br>      Promise.resolve(item)<br>        .then((value) =&gt; {<br>          resolve(value);<br>        })<br>        .catch((reason) =&gt; {<br>          errors[index] = reason;<br>          rejected++;<br>          if (rejected === iterable.length) {<br>            reject(new AggregateError(errors, &quot;All promises were rejected&quot;));<br>          }<br>        });<br>    });<br>  });<br>};</pre><p>4. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race">race() method</a>:</p><p>This method returns a promise that resolves or rejects as soon as the first promise in the iterable settles (either resolves or rejects).</p><pre>Promise.race = function (iterable) {<br>  return new Promise((resolve, reject) =&gt; {<br>    if (iterable.length === 0) {<br>      return;<br>    }<br><br>    iterable.forEach((item) =&gt; {<br>      Promise.resolve(item).then(resolve).catch(reject);<br>    });<br>  });<br>};</pre><p>In this post, I’ve focused on providing a consolidated collection of polyfills for commonly used JavaScript methods, offering a one-stop reference for interview preparation. While I haven’t covered detailed explanations for each method to keep the article concise, the implementations are designed to be clear and straightforward.</p><p>Good luck with your interviews, and Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf3b67e9d951" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Resolving CORS error in your Frond end apps]]></title>
            <link>https://aman-kalra4.medium.com/resolving-cors-error-in-your-frond-end-apps-834f39108585?source=rss-5048408cc855------2</link>
            <guid isPermaLink="false">https://medium.com/p/834f39108585</guid>
            <category><![CDATA[resolvingfrontendissues]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[cors]]></category>
            <dc:creator><![CDATA[Aman Kalra]]></dc:creator>
            <pubDate>Wed, 22 Nov 2023 19:15:18 GMT</pubDate>
            <atom:updated>2023-11-22T19:15:18.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*uPeoVsO8jgEsHa-KjpRx9Q.png" /><figcaption>CROSS ORIGIN RESOURCE SHARING</figcaption></figure><p>When working in Front End projects, there are times when one gets CORS error from APIs, due to which testing or integrating changes becomes difficult.</p><p>But, there is a workaround for this, which can help to overcome the same:</p><p>For Windows, run below command in run dialog box (𝗪𝗶𝗻𝗱𝗼𝘄𝘀 𝗸𝗲𝘆 + 𝗥):<br>𝑐ℎ𝑟𝑜𝑚𝑒.𝑒𝑥𝑒 — 𝑢𝑠𝑒𝑟-𝑑𝑎𝑡𝑎-𝑑𝑖𝑟=”𝐶://𝐶ℎ𝑟𝑜𝑚𝑒 𝑑𝑒𝑣 𝑠𝑒𝑠𝑠𝑖𝑜𝑛” — 𝑑𝑖𝑠𝑎𝑏𝑙𝑒-𝑤𝑒𝑏-𝑠𝑒𝑐𝑢𝑟𝑖𝑡𝑦</p><p>For 𝗠𝗮𝗰, run below command in terminal:<br>𝑜𝑝𝑒𝑛 -𝑛𝑎 𝐺𝑜𝑜𝑔𝑙𝑒\ 𝐶ℎ𝑟𝑜𝑚𝑒 — 𝑎𝑟𝑔𝑠 — 𝑢𝑠𝑒𝑟-𝑑𝑎𝑡𝑎-𝑑𝑖𝑟=/𝑡𝑚𝑝/𝑡𝑒𝑚𝑝𝑜𝑟𝑎𝑟𝑦-𝑐ℎ𝑟𝑜𝑚𝑒-𝑝𝑟𝑜𝑓𝑖𝑙𝑒-𝑑𝑖𝑟 — 𝑑𝑖𝑠𝑎𝑏𝑙𝑒-𝑤𝑒𝑏-𝑠𝑒𝑐𝑢𝑟𝑖𝑡𝑦</p><p>If you use, Microsoft Edge, then you can replace 𝗚𝗼𝗼𝗴𝗹𝗲\ 𝗖𝗵𝗿𝗼𝗺𝗲 as shown below:<br>𝑜𝑝𝑒𝑛 -𝑛𝑎 𝑀𝑖𝑐𝑟𝑜𝑠𝑜𝑓𝑡\ 𝑒𝑑𝑔𝑒 — 𝑎𝑟𝑔𝑠 — 𝑢𝑠𝑒𝑟-𝑑𝑎𝑡𝑎-𝑑𝑖𝑟=/𝑡𝑚𝑝/𝑡𝑒𝑚𝑝𝑜𝑟𝑎𝑟𝑦-𝑒𝑑𝑔𝑒-𝑝𝑟𝑜𝑓𝑖𝑙𝑒-𝑑𝑖𝑟 — 𝑑𝑖𝑠𝑎𝑏𝑙𝑒-𝑤𝑒𝑏-𝑠𝑒𝑐𝑢𝑟𝑖𝑡𝑦</p><p><strong>Note</strong>: Below 𝗲𝘅𝘁𝗲𝗻𝘀𝗶𝗼𝗻 can also serve the purpose:</p><p><a href="https://chromewebstore.google.com/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=en">https://chromewebstore.google.com/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=en</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=834f39108585" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Different Shapes in CSS]]></title>
            <link>https://aman-kalra4.medium.com/different-shapes-in-css-94da1f54be3d?source=rss-5048408cc855------2</link>
            <guid isPermaLink="false">https://medium.com/p/94da1f54be3d</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[css-shapes]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[frontend-development]]></category>
            <dc:creator><![CDATA[Aman Kalra]]></dc:creator>
            <pubDate>Thu, 22 Dec 2022 06:05:15 GMT</pubDate>
            <atom:updated>2022-12-22T06:10:44.226Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O2c5llA5JMICYrHd-CzZrw.png" /><figcaption>Creating Shapes in CSS</figcaption></figure><p>When preparing for interviews for Front end development role, one of the questions in CSS that is usually asked is to draw different shapes.</p><p>In this post I’ll be covering frequently asked ones with required code.</p><h3>Introduction</h3><p>Few of the CSS properties that one needs to know when starting with creating shapes are: <strong>width, height &amp; border</strong>.</p><p>Now, let’s see them one by one:</p><ol><li><strong>Circle</strong></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8756599a237182aea08f219dfdc07276/href">https://medium.com/media/8756599a237182aea08f219dfdc07276/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*5AdBrzZ7rhZs3igM8jXL_w.png" /><figcaption>Circle</figcaption></figure><p>2. <strong>Square</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5727dc39e5ad86499bd9eca5b479059/href">https://medium.com/media/b5727dc39e5ad86499bd9eca5b479059/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*4Pszm7hbhqlO98sM70uErw.png" /><figcaption>Square</figcaption></figure><p>3. <strong>Rectangle</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e8bb0024f0c4766f2df7f23191cbe20/href">https://medium.com/media/1e8bb0024f0c4766f2df7f23191cbe20/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*5UGc2-LZ-1gB19M3fKKBTQ.png" /><figcaption>Rectangle</figcaption></figure><p>4. <strong>Triangle</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d0df0e1535b1cb33e9b7938f28675ad/href">https://medium.com/media/8d0df0e1535b1cb33e9b7938f28675ad/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/124/1*WUSzgLLEXirgAi_WRb7DlA.png" /><figcaption>Triangle</figcaption></figure><p>5. <strong>Inverted Triangle</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e3ddb1e61cd84012f956a5aba12ab36/href">https://medium.com/media/6e3ddb1e61cd84012f956a5aba12ab36/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/116/1*W_4stJYhAbVOZTQ1MVAM1A.png" /><figcaption>Inverted Triangle</figcaption></figure><h3>Bonus Tip!</h3><p>One of the interesting shapes to be made with CSS that I had come across was to make Indian flag tricolour using single div.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/379919d0b8601d936b3d90b2cea6a780/href">https://medium.com/media/379919d0b8601d936b3d90b2cea6a780/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/1*oXIZtWizvMAKM8e7Y5vETw.png" /><figcaption>Tri color</figcaption></figure><h3>Thanks for reading!</h3><p>If you found this article useful, you can show your appreciation by clicking on the clap button and commenting below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94da1f54be3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to TypeScript]]></title>
            <link>https://towardsdev.com/introduction-to-typescript-4df6e75e75c0?source=rss-5048408cc855------2</link>
            <guid isPermaLink="false">https://medium.com/p/4df6e75e75c0</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[what-is-ts]]></category>
            <category><![CDATA[intro-to-typescript]]></category>
            <dc:creator><![CDATA[Aman Kalra]]></dc:creator>
            <pubDate>Mon, 26 Sep 2022 17:57:00 GMT</pubDate>
            <atom:updated>2022-09-27T12:23:31.450Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JZXV89fHRUx-sQMWn25SPg.png" /></figure><p>JavaScript is a dynamic language in which we can assign any type of values to a variable, even create objects of unknown shape.</p><p>And the JavaScript code is interpreted by the browser, so if any error exists in our code, we won’t get to know about it unless the browser throws it i.e. the error gets caught at the run time.</p><p>So, here is when <strong>TypeScript</strong> comes into the picture.</p><p>TypeScript is an open source programming language which is a superset of JavaScript and was developed by Microsoft.</p><p>TypeScript is a strongly typed language that is built on top of JavaScript. It helps us (developers) in catching errors before the code is executed.</p><p>So, TypeScript checks for the type errors when the code is getting compiled.</p><p>For example, when working in JavaScript, if we create an object with properties — <strong>name</strong> and <strong>id</strong> and we try to access a random <strong>getName() </strong>function on that object, then JavaScript doesn’t throw any error at compile time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*PLdvcei2PlWWO4abTU96vg.png" /><figcaption>Object in JavaScript</figcaption></figure><p>But if try the same example in TypeScript, it shows error as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*LtTPvevTMvQ1qGpLWviSsg.png" /><figcaption>Object in TypeScript</figcaption></figure><p>The detailed error is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Tpf0WeqNA3pN6FS3F0jmg.png" /><figcaption>Error in object in TypeScript</figcaption></figure><h3>Types in TypeScript</h3><p>As discussed above, TypeScript helps in static type checking, but how do we assign types in TypeScript.</p><p>We can assign types to a variable just by using a <strong>colon(:)</strong> after the variable name.</p><p>Few of the basic types can be seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf5d7e64aa9b71de8eab2d825281d7b2/href">https://medium.com/media/cf5d7e64aa9b71de8eab2d825281d7b2/href</a></iframe><p>One of the interesting types that we could see above is <strong>any</strong>. <strong>any</strong> signifies that any type of value can be assigned to a variable. But we should try avoid using <strong>any</strong> as it doesn’t serve the exact purpose of using TypeScript.</p><p>Now, let us see on how we can assign types to functions.</p><p>When working with functions, we need to assign types to: <br>a) parameters that a function has<br>b) what function returns</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74dc6a78a3d0bbb5236baae0c88503e2/href">https://medium.com/media/74dc6a78a3d0bbb5236baae0c88503e2/href</a></iframe><p>Above we can see — (name: string): void, this means, getName function takes one parameter — name of type string and doesn’t return any value — void.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a9d582e7b9388ff12fa5641e50986a7/href">https://medium.com/media/8a9d582e7b9388ff12fa5641e50986a7/href</a></iframe><p>If we check now, the syntax (name: string): string means getName function takes one parameter — name of type string and returns a value of type — string.</p><p>In TypeScript, we can even create our own types with the help of <strong>interface.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7dc45a4d9859741e7483f0ddd4003788/href">https://medium.com/media/7dc45a4d9859741e7483f0ddd4003788/href</a></iframe><p>In above example, <strong>Employee</strong> is an interface which contains <strong>id</strong> and <strong>name</strong> as the properties and if we assign <strong>Employee</strong> as a type to an object — <strong>emp</strong>, we get to know that object — <strong>emp</strong> should contain only these properties.</p><p>And addition of new properties gives error as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*XxPJfFAHAHJs2OXCD9FzDw.png" /><figcaption>Error for adding new property</figcaption></figure><p>The detailed error is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4sTlflatQAr54nL6V78KA.png" /><figcaption>Detailed error</figcaption></figure><p>This is because <strong>dept</strong> doesn’t exist in <strong>Employee</strong> interface.</p><p>There are various other types which one would come across while building applications in TypeScript. For reference, you check this <a href="https://www.typescriptlang.org/docs/handbook/basic-types.html">link</a>.</p><h3>Bonus Tip!</h3><p>When working with interfaces in TypeScript, a common operator one sees is ? along with the properties, that means the property is optional and it’s not necessary to be included in the object ‘s structure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/589ca31c0261f8e74dae1769ffe4da12/href">https://medium.com/media/589ca31c0261f8e74dae1769ffe4da12/href</a></iframe><p>To be precise, dept?: string means dept: string | undefined</p><p>Since this post was meant for a brief introduction on TS and its types, I would like to take a pause here.</p><h3>Thanks for reading!</h3><p>If you found this article useful, you can show your appreciation by clicking on the clap button and commenting below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4df6e75e75c0" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/introduction-to-typescript-4df6e75e75c0">Introduction to TypeScript</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Accessibility]]></title>
            <link>https://towardsdev.com/web-accessibility-642efb997901?source=rss-5048408cc855------2</link>
            <guid isPermaLink="false">https://medium.com/p/642efb997901</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[webaccessibilitystandards]]></category>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[accessibility-tools]]></category>
            <category><![CDATA[accessibility-testing]]></category>
            <dc:creator><![CDATA[Aman Kalra]]></dc:creator>
            <pubDate>Wed, 14 Sep 2022 17:38:32 GMT</pubDate>
            <atom:updated>2022-09-15T16:45:33.426Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQhGkiNYbqCvhr4xaPmZyA.png" /><figcaption>Web Accessibility</figcaption></figure><p>Web accessibility is one of the key factors when coming to great user experiences on the web. It is important that a website is accessible by all set of users irrespective of their abilities.</p><blockquote><a href="https://www.w3.org/WAI/">W3C Web Accessibility Initiative (WAI)</a> develops standards for accessibility.</blockquote><h3><strong>What is Web Accessibility?</strong></h3><p>Web accessibility basically means to design and develop websites in a way that people with disabilities can use them easily.</p><p>And with disabilities, we mean anything that affects access to a website, like: visual disability, auditory disability etc.</p><h3>Testing Accessibility for your site</h3><p>To test if a site is accessible and follows the best practices as suggested by <a href="https://www.w3.org/WAI/">WAI</a>, below tools can be used:</p><ol><li><strong>axe DevTools</strong> chrome extension</li><li><strong>JAWS </strong>screen reader</li></ol><p>Let us go through both of these one by one:</p><ol><li><strong>axe DevTools</strong></li></ol><p>If one wants to check if their website is meeting the standards, this extension can be installed in Chrome browser using below link:<br><a href="https://chrome.google.com/webstore/detail/axe-devtools-web-accessib/lhdoppojpmngadmnindnejefpokejbdd"><strong>axe DevTools — Web Accessibility Testing</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PUcuR9ZaBweh2OzstjazjA.png" /><figcaption>axe DevTools</figcaption></figure><p>The extension would suggest us to <strong>scan whole webpage</strong>(available in free version) or <strong>scan a part of our webpage</strong>(available in pro version) and once the scan is done, it would show the issues that are present in the webpage along with suggestions to resolve them.</p><p>2. <strong>Jaws Screen Reader</strong></p><p><a href="https://www.freedomscientific.com/products/software/jaws/">JAWS</a> (<strong>J</strong>ob <strong>A</strong>ccess <strong>W</strong>ith <strong>S</strong>peech), is the one of the most popular screen readers developed for users whose vision disability prevents them from seeing screen content or navigating with mouse. JAWS provides speech for users accessing the computer applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OW0q6RVd7fjIqAjc2-WxIw.png" /><figcaption>JAWS Screen Reader</figcaption></figure><p>And as suggested by axe DevTools, we can debug issues in JAWS by pressing <strong>Insert + F7</strong> to <strong>check links</strong> and <strong>Insert + F6</strong> for <strong>checking headings</strong>.</p><h3>Common Web Accessibility best practices</h3><ol><li>Having proper semantic HTML elements.</li><li>Having alternate text for images.</li><li>Having proper colour contrast between foreground and background.</li><li>Having buttons used wisely.</li><li>Having aria attributes in HTML elements.</li></ol><p>Now, lets discuss all of these, one by one:</p><ol><li><strong>HTML Semantic Elements</strong></li></ol><p>We should consider using semantic elements instead of using div at all places. So that, when a screen reader tries to read out content, the user gets to know that the content is a header, footer, article, section or a navigation (nav).</p><p>2. <strong>Alternate text for images</strong></p><p>We should always consider providing an alt text for images present in web page, so that screen readers can easily read out the text for users with visual disability.</p><p>3. <strong>Color Contrast</strong></p><p>We should always be sure that the contrast between the foreground and background should be enough so that people with colour blindness would be able to distinguish easily.</p><p>By enough, I mean, it should either be <strong>AA</strong> or <strong>AAA. </strong><strong>A</strong>, <strong>AA</strong> and <strong>AAA</strong> are the<strong> </strong>levels of conformance. <strong>A</strong> being the lowest, <strong>AA</strong> being mid range, and <strong>AAA</strong> being highest.</p><p>4. <strong>Buttons Usage</strong></p><p>We should always use button for having click functionality and avoid using other HTML elements as buttons. But if in any case, we want to have it used for other HTML elements, we can add role=&quot;button&quot; and tabindex=&quot;0&quot;, so that, it’s easy for screen readers to announce.</p><p>5. <strong>Aria attributes</strong></p><p>We should include aria attributes in HTML elements. These help to provide more description to elements that we use in our page. And the same would be shown by axe DevTools in case missed.</p><p><strong>Example</strong>: If we use a div as progress bar, then we can add role = “progressbar” as an attribute in the div which allows screen reader to announce to the user. Similarly, we can add aria-valuemin=”0&quot;, aria-valuemax=&quot;100&quot; and aria-valuenow=”50&quot; for better user experience.</p><pre>&lt;div<br> role=”progressbar”<br> aria-valuemin=”0&quot;<br> aria-valuemax=”100&quot;<br> aria-valuenow=”50&quot;&gt;<br>&lt;/div&gt;</pre><blockquote><strong>Note</strong>: There are many other points to be kept in mind while making a site accessible, but I’ve covered only few in this blog.</blockquote><h3>Bonus Tip!</h3><p>Lets’ suppose we have a text with colour: red and background-color: blue(I know these colours are bit weird, but for example I’ve considered this :P)</p><p>There would be a colour contrast issue in axe DevTools when we run scan of our page. And there’s an easy way to resolve this:</p><p>a) Inspect element with the issue.</p><p>b) Follow the steps as shown in below video:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fflashydisastrousitalianbrownbear&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Fflashydisastrousitalianbrownbear&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FFlashyDisastrousItalianbrownbear-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="3024" height="1226" frameborder="0" scrolling="no"><a href="https://medium.com/media/923b81bad017f28c6bb11c5524d616dd/href">https://medium.com/media/923b81bad017f28c6bb11c5524d616dd/href</a></iframe><h3>Thanks for reading!</h3><p>If you found this article useful, you can show your appreciation by clicking on the clap button and commenting below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=642efb997901" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/web-accessibility-642efb997901">Web Accessibility</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[useCallback hook — React]]></title>
            <link>https://towardsdev.com/usecallback-hook-react-f49dc386bf47?source=rss-5048408cc855------2</link>
            <guid isPermaLink="false">https://medium.com/p/f49dc386bf47</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[memoization]]></category>
            <category><![CDATA[usecallback]]></category>
            <category><![CDATA[react-memo]]></category>
            <dc:creator><![CDATA[Aman Kalra]]></dc:creator>
            <pubDate>Mon, 22 Aug 2022 19:52:06 GMT</pubDate>
            <atom:updated>2022-08-24T07:27:34.385Z</atom:updated>
            <content:encoded><![CDATA[<h3>useCallback hook — React</h3><p>When working in React, every developer comes across — useCallback() hook.<br>And in this post, I’ll try to cover how we can use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hHn9DOggfHWdw2ERuphexQ.png" /></figure><p>Before proceeding, first let’s try to see what is React.memo()?</p><blockquote>React.memo is basically a <strong>Higher Order Component </strong>(function that takes a component as an input and returns modified version of that component)</blockquote><blockquote>If a component renders <strong>same result</strong> with <strong>same props</strong> each time, we can wrap it in <strong>React.memo()</strong> which would help us to <strong>memoize</strong> the result. And then, React uses the result that was rendered last time, thus preventing re-rendering of the component.</blockquote><blockquote>React.memo() is similar to <strong>React.PureComponent</strong> that is used in class components.</blockquote><p>So, let’s start with a basic example on how we would pass props from parent to child:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be5ff4dd8f11de4d9bef49ba93d928b1/href">https://medium.com/media/be5ff4dd8f11de4d9bef49ba93d928b1/href</a></iframe><p>Let’s try to see whats happening in above code:</p><p>We are passing name and sendDataToChild props to Child component. But whenever, we type something in the input field, handleChange function gets called, which re-renders the Parent component by calling setValue(). But if we check in console, we get the log of &quot;child component” every time we type something.</p><p>So, let’s see why Child component is getting rendered again and again instead of component being memoized with the help of memo().</p><p>We might think that the props that are being sent to Child component are never changing, and React.memo() should be able to solve re-rendering issue by using the <strong><em>result that was rendered last time</em></strong>. But that isn’t true, because on every render of Parent component, sendDataToChild function gets recreated, which means, all props are not same and which does not fulfil the condition of React.memo().</p><p>So, to solve above issue, we need to have single instance of sendDataToChild between all re-renders of Parent component.</p><p>Now, let’s see how that can be achieved:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06f743dcd3a024fa7873614f2af8a7a6/href">https://medium.com/media/06f743dcd3a024fa7873614f2af8a7a6/href</a></iframe><blockquote><strong>What useCallback() actually is?</strong></blockquote><blockquote><strong>Syntax</strong>: useCallback(callbackFunction, dependencyArray)</blockquote><blockquote>useCallback takes a callback function and a dependency array as its params. And, it returns a memoized version of the callbackFunction and that would only change if anything in the dependencyArray changes.</blockquote><p>In above code, useCallback() helps us to maintain single instance of the function between re-rendering of the Parent component. The reference of the callback function — () =&gt; { console.log(“data to child”); } gets created at the time component gets mounted (as <strong><em>empty dependency array</em></strong> is used) and remains same even if Parent component re-renders. And then, React.memo() helps in preventing the Child component from re-rendering.</p><blockquote><strong>Note</strong>: Here for the simplicity, I had used <strong>empty dependency array</strong>, but wrt the use case, we can have something specified in dependency array as well.</blockquote><p>useCallback() and React.memo() are one of the important concepts in React which help us to increase performance of our application. And they are one of the frequently asked questions in interviews as well.</p><blockquote><strong>Note: </strong>React.memo() proves to be helpful for performance boost, but, we should be aware on when to use it, because if we use it with every component, then prop comparison would take place every time and that would not be efficient.</blockquote><h3>Thanks for reading!</h3><p>If you found this article useful, you can show your appreciation by clicking on the clap button and commenting below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f49dc386bf47" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/usecallback-hook-react-f49dc386bf47">useCallback hook — React</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Function Currying]]></title>
            <link>https://towardsdev.com/function-currying-f811946e6a78?source=rss-5048408cc855------2</link>
            <guid isPermaLink="false">https://medium.com/p/f811946e6a78</guid>
            <category><![CDATA[currying]]></category>
            <category><![CDATA[infinite-currying]]></category>
            <category><![CDATA[function-currying]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-currying]]></category>
            <dc:creator><![CDATA[Aman Kalra]]></dc:creator>
            <pubDate>Fri, 10 Jun 2022 03:37:39 GMT</pubDate>
            <atom:updated>2022-06-14T06:40:55.720Z</atom:updated>
            <content:encoded><![CDATA[<p>Function Currying is yet another topic that sometimes creates a confusion while going through for the first time. <br>In this post, I’ll discuss on what currying is and how we can implement it in JavaScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*7cDGlPYSmut-kr_FK52MmA.png" /><figcaption>Currying in JavaScript</figcaption></figure><h4>What currying is?</h4><p>Currying means breaking down a function (which takes multiple arguments) into a series of functions which take only one argument.</p><p>That might be confusing. Let’s get this cleared with the help of examples:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1b3e5bdb91307c6b5c298fad425c4bd/href">https://medium.com/media/e1b3e5bdb91307c6b5c298fad425c4bd/href</a></iframe><p>If we see above, add(1) on line 9returns a function:</p><pre>return function(b){  <br>    return function(c){   <br>        return a+b+c  <br>    } <br>}</pre><p>and so does res1(2) on line 10:</p><pre>return function(c){   <br>    return a+b+c  <br>}</pre><p>And now, since the above function is present in res2, and when we invoke it: res2(3) on line 11, it does the calculation with the previous arguments received:</p><pre>a = 1 and b = 2</pre><p>And now, we get the output as:result: 6 on line 12.</p><p>Now, there might be a confusion, how the values of initial returned functions are accessible inside the last returned function, <strong>that is due to</strong> <strong>closures</strong>.</p><p>Above code could be re-written as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a545abbdd1d4af7f25f81aac55efa58/href">https://medium.com/media/2a545abbdd1d4af7f25f81aac55efa58/href</a></iframe><p>Since, returning functions to new variables again and again, would take many variables, so, we can write it in a better way as mentioned above.</p><blockquote><strong>Note: </strong>Here we have broken down the add function into a series of functions each taking single argument.</blockquote><p>Now, what if we want to increase the number of parameters passed, then having <strong>n</strong> <strong>number</strong> of functions returned won’t be a feasible way, so we can re-write above code in a generic way, like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1faeafffd8c34f5120a3af21da115084/href">https://medium.com/media/1faeafffd8c34f5120a3af21da115084/href</a></iframe><p>If we see above code, it also gives us the same result.</p><p>In above approach, we can see that there’s an empty parenthesis at the end of <strong>add(1)(2)(3)()</strong> on line 10. Let’s see why:</p><p>Here, we are returning a function which in-turn returns another function to accept next argument and so on. But we stop the returning of function once last argument doesn’t exist (i.e. we have an empty parenthesis), where condition on line 3 fails and line 6 gets executed.</p><p>Currying is one of the concepts that JavaScript developers come across one time or the other. And it’s one of the frequently asked questions in JavaScript interviews as well.</p><h3>Bonus Tip!</h3><p>There might be times, where we might come across a term: <strong>infinite currying</strong>. So, let’s see in code, how that can be implemented:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7157f408bc153beab34d83f2f17c41a8/href">https://medium.com/media/7157f408bc153beab34d83f2f17c41a8/href</a></iframe><p>Here, we are using the same logic as in the last example: <strong>currying-3.js</strong>, except, here we are using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameters</a>, which help us to take all arguments as an array and upon which we can perform the operation(addition in our case). And addition, here, is done with the help of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce">reduce()</a> method.</p><h3>Thanks for reading!</h3><p>If you found this article useful, you can show your appreciation by clicking on the clap button and commenting below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f811946e6a78" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/function-currying-f811946e6a78">Function Currying</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event Loop in JavaScript]]></title>
            <link>https://medium.com/walmartglobaltech/event-loop-in-javascript-a932f1d8070e?source=rss-5048408cc855------2</link>
            <guid isPermaLink="false">https://medium.com/p/a932f1d8070e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[event-loop-in-js]]></category>
            <category><![CDATA[micro-tasks]]></category>
            <category><![CDATA[macrotask]]></category>
            <dc:creator><![CDATA[Aman Kalra]]></dc:creator>
            <pubDate>Wed, 26 Jan 2022 21:17:52 GMT</pubDate>
            <atom:updated>2025-09-09T13:40:34.215Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WyvoDHWlqI08juTOOntMgA.png" /></figure><p>When working with JavaScript, understanding the event loop is crucial. Given that JavaScript is a single-threaded language, various confusions often arise around how it handles asynchronous operations. In this blog, let’s cover event loop in detail, step by step.</p><p>JavaScript is a single-threaded language, meaning only one task can run at a time. In other words, JavaScript executes one line of code at a time.</p><p>Imagine needing to run an asynchronous operation, such as fetching data from an API, which takes around 30 seconds. Waiting for 30 seconds before anything else can happen is far from ideal. This is where the concept of the event loop comes into the picture.</p><p>Let’s break down the core concepts before diving into the event loop’s functionality</p><h4><strong>Execution Stack/ Call Stack</strong></h4><p>The execution stack in JavaScript is like a stack in data structures, following the <strong>LIFO</strong> (Last In, First Out) principle. It keeps track of function calls. When a function is invoked, it’s pushed onto the stack, and once it completes, it’s popped off.</p><h4><strong>Web APIs</strong></h4><p>Web APIs provide functions that browsers offer for use in web applications. Examples include setTimeout, fetch, HTTP requests, localStorage, geolocation, etc.</p><h4><strong>Message Queue/ Callback Queue/ Event Queue</strong></h4><p>The message queue is similar to a queue in data structures, following the <strong>FIFO</strong> (First In, First Out) principle. In JavaScript, when an asynchronous task completes, it’s pushed into the queue, and the function waits for its turn to be executed in the execution stack.</p><h3>Example</h3><p>Now, let’s understand above concepts with the help of an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1535be166a9fd8ed5744d0708c595a3c/href">https://medium.com/media/1535be166a9fd8ed5744d0708c595a3c/href</a></iframe><pre>Hey, I am first statement<br>Hey, I am second statement<br>Hey, I am third statement // after 1 second</pre><h4><strong>Working</strong></h4><ol><li>The first() function at <strong>line</strong> <strong>13</strong> and it gets pushed onto the <strong>Execution Stack</strong>. After logging <strong>Hey, I am first statement</strong> to the console, its execution completes, and it is popped off the stack.</li><li>Next, on <strong>line</strong> <strong>14</strong>, the setTimeout() is called with a delay of 1000ms (1s) and a callback function third(). The setTimeout() itself gets pushed onto the <strong>Execution Stack</strong>.</li><li>However since setTimeout() is part of <strong>Web APIs</strong>, it sets up the timer and third() function is handed off to the <strong>Web API</strong> environment to wait for the 1s timer to complete.</li><li>Now, at <strong>line 15</strong>, second() function is called and pushed onto the <strong>Execution Stack</strong>. It logs <strong>Hey, I am second statement</strong> to the console, completes its execution, and is popped off the stack.</li><li>Now, let’s assume, the timer of 1s has been completed, now third() function moves from <strong>Web APIs</strong> to <strong>Message Queue</strong>.</li><li>At this point, the <strong>Execution Stack</strong> is empty since all synchronous functions have completed their execution.<br>And third() function is in <strong>Message Queue</strong>, waiting to be executed. Here is where the <strong>Event Loop </strong>steps in.</li><li>Now, event loop checks the <strong>Message Queue</strong> and finds the third() function and pushes it onto the <strong>Execution Stack</strong>.</li><li>And, the third() function logs <strong>Hey, I am third statement</strong> to the console completes its execution, and is then popped off the stack.</li></ol><p><strong>Note</strong>: Imagine, if we change above example like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a65417f817fcddf7349b95b23bd403e2/href">https://medium.com/media/a65417f817fcddf7349b95b23bd403e2/href</a></iframe><p>If the second() function is passed as a callback to setTimeout() like this: <strong>setTimeout(second, 3000)</strong>, the order of execution will change. The output would then be:</p><pre>Hey, I am first statement<br>Hey, I am third statement // after 1 second<br>Hey, I am second statement // after 3 seconds</pre><p>Thus, the order of execution can change depending upon how long your task would take to execute.</p><h4>Internal Working</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*2yNStnHPu1kGMDSNJYBNsA.jpeg" /><figcaption>When event loop checks that execution stack is empty, callback function third(), is sent to execution stack</figcaption></figure><blockquote><strong>Event loop</strong> keeps monitoring the execution stack and message queue. Whenever execution stack is empty, the first item in the message queue gets added to the execution stack.</blockquote><p>This example demonstrates how asynchronous operations are performed using setTimeout and how the event loop helps manage these operations in a simple and efficient way. Similarly, any asynchronous operation, like a Promise, is also handled by the event loop.</p><p>Speaking of <strong>Promises</strong>, there’s an important concept related to the event loop: <strong>Microtasks</strong> and <strong>Macrotasks</strong>. Let’s explore what these are.</p><h3>Microtasks and Macrotasks</h3><p>JavaScript uses <strong>Microtasks</strong> and <strong>Macrotasks</strong> to prioritize various asynchronous operations. Now, let us see each in detail.</p><p><strong>Microtasks</strong> are tasks that have higher priority and are executed immediately after the currently executing task, but before the next macrotask. <strong>Examples</strong> of microtasks include: <strong>Promises</strong>, <strong>Mutation Observers</strong>.</p><p><strong>Macrotasks</strong> are tasks that have a lower priority and are executed after all the currently queued microtasks are completed. <strong>Examples</strong> of macrotasks include: <strong>setTimeout</strong>, <strong>setInterval</strong>, and <strong>I/O operations</strong>.</p><p>Thus, <strong>Microtasks</strong> execute before the <strong>Macrotasks</strong> ensuring higher-priority tasks are completed first. This helps in maintaining a smooth and responsive UI while efficiently managing different types of tasks in the event loop.</p><h3>Example</h3><p>Let’s look at the example below to understand this better.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14953cf0796588e14d0af02af2e56713/href">https://medium.com/media/14953cf0796588e14d0af02af2e56713/href</a></iframe><p><strong>Output</strong> for above example:</p><pre>First Statement<br>Last Statement<br>Promise Statement<br>Timeout Statement</pre><h4>Working</h4><ol><li>First of all, first synchronous statement is executed</li></ol><pre>console.log(&quot;First statement&quot;);</pre><p>printing — <strong>First Statement</strong></p><p>2. Next, the setTimeout function is called with a delay of <strong>0 milliseconds</strong>. Although the delay is <strong>0</strong>, setTimeout is classified as a <strong>Macrotask</strong> and is handled by the Web APIs environment. The callback function for setTimeout is sent to the <strong>Macrotask</strong> queue to be executed later.</p><pre>setTimeout(() =&gt; {<br>  console.log(&quot;Timeout statement&quot;);<br>}, 0);</pre><p>3. Now, Promise.resolve().then() method is called next. Promises are classified as <strong>Microtasks</strong>. The callback function inside then is queued to the <strong>Microtask</strong> queue to be executed immediately after the current synchronous operations complete.</p><pre>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;Promise statement&quot;);<br>});</pre><p>4. Now, the last synchronous statement is executed</p><pre>console.log(&quot;Last statement&quot;);</pre><p>printing — <strong>Last Statement</strong></p><p>5. After all the synchronous code has been executed, the event loop checks the <strong>Microtask</strong> queue before proceeding to the <strong>Macrotask </strong>queue. The Promise callback in the <strong>Microtask</strong> queue gets executed now, printing — <strong>Promise statement</strong></p><p>6. Finally, the event loop moves to the macrotask queue where the <strong>setTimeout</strong> callback is present, and thus printing — <strong>Timeout statement</strong>.</p><h3>Conclusion</h3><p>The event loop is crucial for understanding how asynchronous operations work in JavaScript. It continuously monitors the execution stack and manages both the Microtask and Macrotask queues, ensuring that tasks are executed efficiently.</p><p>A better understanding of event loop would help you to understand how synchronous and asynchronous operations are handled in JavaScript.</p><h3>Thanks for reading!</h3><p>If you found this article useful, do like, comment and share it with your friends and colleagues.</p><p>If you like to see similar tips in HTML, CSS, JavaScript and React, do <a href="https://www.linkedin.com/in/amankalra1">Follow me on LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a932f1d8070e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/walmartglobaltech/event-loop-in-javascript-a932f1d8070e">Event Loop in JavaScript</a> was originally published in <a href="https://medium.com/walmartglobaltech">Walmart Global Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debouncing in JavaScript]]></title>
            <link>https://aman-kalra4.medium.com/debouncing-in-javascript-96182561a7dd?source=rss-5048408cc855------2</link>
            <guid isPermaLink="false">https://medium.com/p/96182561a7dd</guid>
            <category><![CDATA[debouncing-in-js]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[debouncing]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Aman Kalra]]></dc:creator>
            <pubDate>Sun, 23 May 2021 11:23:35 GMT</pubDate>
            <atom:updated>2021-05-25T05:18:29.783Z</atom:updated>
            <content:encoded><![CDATA[<p>Debouncing being one of the most frequently asked questions in JS interviews is considered a bit tricky topic. But in this post, I’ll try to make it a simpler one for the readers.</p><p><strong><em>What does debouncing mean?<br></em></strong>In lay man words, I would explain debouncing as a technique to reduce unnecessary computations or to limit the rate of computations.</p><p><strong><em>Use Case:</em></strong></p><p>Just imagine, we are building a search box and while the user types a character in search box, the suggestions for the related words should come. (<strong>eg</strong>: think of searching something on Amazon/ Flipkart). So, if we assume, the suggestions would come through an API; so on every key stroke, the API would get hit. But this won’t be a better approach in real time.</p><p>So, to avoid above scenario’s behavior(behavior of calling APIs on every keystroke), we can use debouncing.</p><p><strong><em>Example:</em></strong></p><p>Let’s assume we have a text box like the one shown below:</p><pre>&lt;input type=&quot;text&quot; onkeyup=&quot;handleChange()&quot; /&gt;</pre><p>In the above text box, on every key up event, the <em>handleChange()</em> function would be called.</p><pre>const handleChange = () =&gt; {<br>      /*calling API on every key up event*/<br>      console.log(&#39;API called!&#39;);<br>}</pre><p>The way above code works is not an optimized way, since we are calling API on every key up event. So, lets see debouncing solution now.</p><p><strong><em>Debouncing Solution:</em></strong></p><p>Some prerequisites required before jumping on to the concept:<br>1. Closures<br>2. setTimeout()<br>3. clearTimeout()<br>4. <strong><em>this </em></strong>keyword<br>5. apply() method (Function’s prototype method)</p><p>Now, lets define <em>handleChange()</em> function in an optimized way:</p><pre>const debounceFunction = (fn, time) =&gt; {<br>  let timerID;<br>  return function() {<br>    clearTimeout(timerID);<br>    timerID = setTimeout(() =&gt; { <br>          fn.apply(this, [&#39;debounce&#39;]);<br>         }, time);<br>  };<br>}</pre><pre>const getAPIData = (...args) =&gt; { <br>   /*calling API in an optimized way*/<br>   console.log(`Call an API ${args[0]}`);<br>}</pre><pre>const handleChange = debounceFunction(getAPIData, 300);</pre><p><strong><em>Note</em>: </strong>In the above solution, we need to call the API only when difference between key up events is 300 <strong>ms</strong>(milliseconds).</p><p>To understand the above code, lets go through it in different parts:</p><ol><li>Since functions are first class citizens in JS, we can pass them as parameters as well. So, in debounceFunction(), we are passing function -getAPIData(the function that needs to be optimized) as parameter. And, we would pass time in <strong>milliseconds </strong>which setTimeout would use.</li><li>Inside debounceFunction()we would create a timerID variable which would hold the value returned by setTimeout (setTimeout returns the a value that we can use to cancel the execution.)<br>The reason why timerID is created outside returned function is that, debounceFunction() forms a closure and since closure helps us to persist the value even after the function is returned.</li><li>Due to closures, the value returned by setTimeout is persisted and until a new key up event is encountered clearTimeout keeps on cancelling the old timerID values and setTimeout keeps on assigning new values to timerID. But as soon as the key up event takes place and time specified in <strong>milliseconds </strong>is passed, setTimeout executes successfully without getting cancelled and thus calling getAPIData in an optimized way.</li></ol><p><strong><em>Importance of above solution in lay man words:</em></strong></p><p>So, now when a user types up words in text box within the time specified in <strong>milliseconds</strong>,<strong> </strong>the API method wont hit on every key up event, rather the API method would be hit only once the time interval is covered or if the difference between key up events is equal to the time specified.</p><p><strong><em>Note:</em></strong></p><ol><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout"><em>setTimeout()</em></a><em>:</em><br>It sets a timer which executes a function or specified piece of code once the timer expires.<br><strong>Note: </strong>It returns a <strong>timerID</strong> that we can use to cancel the execution.</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout"><em>clearTimeout()</em></a><em>:</em><br>It cancels a timeout previously established by calling setTimeout.<br><strong>Note:</strong> It takes <strong>timerID </strong>returned by setTimeout() as the <strong>parameter.</strong></li></ol><p>Hope you enjoyed and understood my piece of writing.<br>Do comment and let me know if you see any scope of improvement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96182561a7dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>