<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: TusharShahi</title>
    <description>The latest articles on Forem by TusharShahi (@tusharshahi).</description>
    <link>https://forem.com/tusharshahi</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F486783%2F6ada7af5-1aa7-4488-98c1-81b45d88dcd9.png</url>
      <title>Forem: TusharShahi</title>
      <link>https://forem.com/tusharshahi</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/tusharshahi"/>
    <language>en</language>
    <item>
      <title>React Hooks: Default Export vs Named Export</title>
      <dc:creator>TusharShahi</dc:creator>
      <pubDate>Sun, 25 Jan 2026 07:32:19 +0000</pubDate>
      <link>https://forem.com/tusharshahi/react-hooks-default-export-vs-named-export-1edn</link>
      <guid>https://forem.com/tusharshahi/react-hooks-default-export-vs-named-export-1edn</guid>
      <description>&lt;p&gt;Both default and named exports have their pros and cons. In Javascript codebases, it mostly comes down to personal choice and consistency. I also never felt strongly about one over the other - until I saw this one error.&lt;/p&gt;

&lt;h2&gt;
  
  
  Problem
&lt;/h2&gt;

&lt;p&gt;The error was minified error &lt;a href="https://react.dev/errors/310" rel="noopener noreferrer"&gt;#310&lt;/a&gt; - React detected more hooks in a render than the previous one. This usually happens when React hooks are called conditionally.&lt;/p&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Component = () =&amp;gt; {
....
if(someCondition)
 return &amp;lt;p&amp;gt;Testing&amp;lt;/p&amp;gt;;
const value = useHook(); //breaks one of React's rules. ESLint gives an error
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Usually, ESLint throws an error for such hook invocations, courtesy of the plugin - &lt;a href="https://www.npmjs.com/package/eslint-plugin-react-hooks" rel="noopener noreferrer"&gt;eslint-plugin-hooks-rules&lt;/a&gt;. So this code would be caught before it can be committed to main.&lt;/p&gt;

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

&lt;p&gt;But in this failing scenario, it did not happen. The reason is that hook was imported like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import getItemConfig from '../config/hooks/item';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The default export from the file is a hook. But it was named something else and imported. If getItemConfig is used conditionally, ESLint rules cannot flag it. &lt;strong&gt;The rules rely on the &lt;code&gt;use&lt;/code&gt; prefix.&lt;/strong&gt; That is why it is important to create custom hooks that start with the prefix &lt;code&gt;use&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Fix
&lt;/h2&gt;

&lt;p&gt;Fixing the issue is straightforward. Ensure that the hook is never called conditionally. In this case, move it above the return statement. &lt;/p&gt;

&lt;p&gt;If your hook makes a network call that you wanted to prevent and hence it was after the return statement, then consider breaking the component into two. &lt;/p&gt;

&lt;p&gt;The rule of React enforcing the number and order of hooks to be called to be the same is only within a React component boundary.&lt;/p&gt;

&lt;h2&gt;
  
  
  Preventing future occurences
&lt;/h2&gt;

&lt;p&gt;As next steps, we should ensure that hooks are always imported as hooks - functions with prefix &lt;code&gt;use&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;We can try to ensure that in our code reviews, but that might not be fool proof as the hook might be committed separately and the usage might be committed in a different commit.&lt;/p&gt;

&lt;p&gt;There is no direct advantage of using a default export, and the one advantage we have - renaming an import to anything the developer wants - ended up becoming a disadvantage for us. &lt;/p&gt;

&lt;p&gt;We decided to follow the approach for disabling default exports, only for hook files. Note that this does not completely solve the problem. Because even in named exports, one can do the below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useGetConfig as getItemConfig } from '../config/hooks/item';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But this is more intentional and easier to catch in code reviews. &lt;/p&gt;

</description>
      <category>webdev</category>
      <category>react</category>
      <category>programming</category>
      <category>javascript</category>
    </item>
    <item>
      <title>HTML Text Fragments 🪄</title>
      <dc:creator>TusharShahi</dc:creator>
      <pubDate>Tue, 17 Jun 2025 15:51:59 +0000</pubDate>
      <link>https://forem.com/tusharshahi/html-text-fragments-nod</link>
      <guid>https://forem.com/tusharshahi/html-text-fragments-nod</guid>
      <description>&lt;p&gt;In HTML, every anchor link acts as a bookmark on the page. Besides acting as a link to another page, it also acts as a checkpoint on that particular page. &lt;/p&gt;

&lt;p&gt;Given a &lt;a href="https://developer.mozilla.org/en-US/docs/Web/URI/Reference/Fragment" rel="noopener noreferrer"&gt;page&lt;/a&gt;, one can automatically jump to a particular section of the page, like &lt;a href="https://developer.mozilla.org/en-US/docs/Web/URI/Reference/Fragment#examples" rel="noopener noreferrer"&gt;this&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;This has been a feature as long as I can remember and has been a convenient way to share resources and engage in conversations.&lt;/p&gt;

&lt;h2&gt;
  
  
  Text Fragments
&lt;/h2&gt;

&lt;p&gt;Today, I discovered text fragments (available since 2020 in some browsers). With Text Fragments, you can directly link to any portion of text in another web document. The biggest advantage is that it does not matter if the author of the document has annotated it with an ID. All you need to add in the URL is the text.&lt;/p&gt;

&lt;p&gt;No more anchors ⚓.&lt;/p&gt;

&lt;p&gt;This flexibility is amazing and would be a game changer in many fields of work. Here is an &lt;a href="https://developer.mozilla.org/en-US/docs/Web/URI/Reference/Fragment/Text_fragments#:~:text=reality" rel="noopener noreferrer"&gt;example&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;The specification mentions that the browser is supposed to highlight the text to make for easy detection.&lt;/p&gt;

&lt;h2&gt;
  
  
  Popular use cases
&lt;/h2&gt;

&lt;p&gt;Google has embraced the text fragment standard in its search page. The feature is right there. In hindsight, it seems obvious that something like this always existed.&lt;/p&gt;

&lt;p&gt;For example, the first result of a search like &lt;a href="https://www.google.com/search?q=when+did+google+go+ipo&amp;amp;sca_esv=160fa51d20ac9224&amp;amp;rlz=1C5GCCM_en&amp;amp;sxsrf=AE3TifMIREQj_usHV3QXRiOSPXxK-BQDnw%3A1750174250914&amp;amp;ei=KopRaMbMN8ihseMPuqqO0AM&amp;amp;ved=0ahUKEwjGiZWU4_iNAxXIUGwGHTqVAzoQ4dUDCBA&amp;amp;uact=5&amp;amp;oq=when+did+google+go+ipo&amp;amp;gs_lp=Egxnd3Mtd2l6LXNlcnAiFndoZW4gZGlkIGdvb2dsZSBnbyBpcG8yBhAAGAcYHjILEAAYgAQYhgMYigUyCxAAGIAEGIYDGIoFMgsQABiABBiGAxiKBTIIEAAYgAQYogQyCBAAGIAEGKIEMggQABiABBiiBDIIEAAYgAQYogRIpAhQqwNY1QdwAngBkAEAmAGVAaAB8ASqAQMwLjW4AQPIAQD4AQGYAgSgAvEBwgIKEAAYsAMY1gQYR8ICBRAAGO8FmAMAiAYBkAYIkgcDMi4yoAf5GbIHAzAuMrgH7QHCBwUwLjMuMcgHCg&amp;amp;sclient=gws-wiz-serp" rel="noopener noreferrer"&gt;When did google go ipo&lt;/a&gt; always takes you to the exact &lt;a href="https://en.wikipedia.org/wiki/Google#:~:text=On%20August%2019%2C%202004%2C%20Google,via%20an%20initial%20public%20offering." rel="noopener noreferrer"&gt;text&lt;/a&gt; with answer.&lt;/p&gt;

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

&lt;p&gt;When you click on the first result, you land here:&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7xrtjqjfp9s00gyuzo3o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7xrtjqjfp9s00gyuzo3o.png" alt="When you click on the first result, you land here" width="800" height="150"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Syntax
&lt;/h2&gt;

&lt;p&gt;The link is supposed to be of this format:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;https://example.com#:~:text=[prefix-,]textStart[,textEnd][,-suffix]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This &lt;code&gt;#:~:text=&lt;/code&gt; is slightly different than &lt;code&gt;#&lt;/code&gt;, which is for a document fragment. &lt;/p&gt;

&lt;p&gt;The support is quite extensive. One can check for textStart, textEnd, and even the prefix &amp;amp; suffix of the text. So it becomes easier to link to a substring when there are multiple instances. Here is an &lt;a href="https://example.com/#:~:text=asking-,for" rel="noopener noreferrer"&gt;example&lt;/a&gt;(pun intended).&lt;/p&gt;

&lt;p&gt;Of course, one has the option to decide what the style of a text target looks like with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;::target-text {
background-color: yellow;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While the feature is great for website developers, I believe it is as important if you are not a developer and just share/save online documents. Now that 92% of browsers support it, we might see more usage soon.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>html</category>
      <category>programming</category>
      <category>learning</category>
    </item>
    <item>
      <title>Transient Activation: Why the copy button did not work on iPhone</title>
      <dc:creator>TusharShahi</dc:creator>
      <pubDate>Fri, 23 May 2025 21:27:54 +0000</pubDate>
      <link>https://forem.com/tusharshahi/transient-activation-why-our-apps-copy-button-did-not-work-on-iphone-4ba0</link>
      <guid>https://forem.com/tusharshahi/transient-activation-why-our-apps-copy-button-did-not-work-on-iphone-4ba0</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;We recently faced a weird bug at my previous company: our app's copy button decided to take a vacation, but only on iPhones. If you're aware of Safari's quirky ways with the Clipboard API, feel free to skip. Otherwise carry on, this write-up might save you some time in the future.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Feature: A Simple "Save and Copy"
&lt;/h2&gt;

&lt;p&gt;Let's set the scene. We'd introduced a handy modal where users could update a setting and then instantly copy a generated link. Think Google Sheets' share functionality: you tweak sharing permissions, then grab the link.&lt;/p&gt;

&lt;p&gt;Our process was straightforward:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;A server call to update the setting.&lt;/li&gt;
&lt;li&gt;A copy operation to grab the shiny new link.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A dumbed-down version of the code for our CTA handler looked like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const handleUpdateSetting = async () =&amp;gt; {
  const updatedLink = await saveSetting(updateValue); // Save the setting and get the link
  if (window.navigator.clipboard) {
    await window.navigator.clipboard.writeText(updatedLink); // Attempt to copy
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;"Easy peasy," I thought. I figured I had a solid grasp of both operations. Boy, was I wrong.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Problem: "Settings Saved, But Link Could Not Be Copied"
&lt;/h2&gt;

&lt;p&gt;During testing, iPhones consistently failed to copy the link. Thankfully, our toast messages were on point: "Settings saved but link could not be copied." Our logs also showed a &lt;code&gt;NotAllowedError&lt;/code&gt; for the copy operation.&lt;/p&gt;

&lt;p&gt;Most of our development and testing happened in Chrome. I did not test on Safari, as &lt;strong&gt;it was just the clipboard the API, which I already knew right?&lt;/strong&gt; While browsers adopted the Clipboard API, they did so with a keen eye on user security, aiming to prevent scripts from copying text without explicit user intent. The weird thing was, this wasn't an unprompted copy, and we had dozens of other places where this exact &lt;code&gt;writeText&lt;/code&gt; call worked perfectly.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Culprit: Transient User Activation
&lt;/h2&gt;

&lt;p&gt;A glance into the &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API" rel="noopener noreferrer"&gt;Clipboard API&lt;/a&gt; documentation quickly unearthed the root cause. Different browsers, it turns out, have varying security requirements for this API:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Secure Contexts Only: (Universal) The API needs a secure context.&lt;/li&gt;
&lt;li&gt;clipboard-write Permission: (Chromium specific) Browsers like Chrome require explicit permission.&lt;/li&gt;
&lt;li&gt;Transient Activation: (Firefox, Safari – BINGO!) This was our problem.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So, what exactly is transient activation? Imagine a quick window of opportunity after a user directly interacts with your page – a button click, a mouse movement, a menu selection. Certain features, like &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen" rel="noopener noreferrer"&gt;&lt;code&gt;Element.requestFullscreen()&lt;/code&gt;&lt;/a&gt; and our problematic &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText" rel="noopener noreferrer"&gt;&lt;code&gt;Clipboard.writeText()&lt;/code&gt;&lt;/a&gt;, are "gated" by this transient activation. They'll only work if executed within that brief window.&lt;/p&gt;

&lt;p&gt;Every user agent has a property &lt;strong&gt;transient activation duration&lt;/strong&gt; – a short, fixed period after a user interaction during which this "activation" is valid. In our case, &lt;code&gt;Clipboard.writeText&lt;/code&gt; was being executed after a Promise resolved (the saveSetting call). Depending on network conditions, this delay could be anywhere from a hundred milliseconds to a few seconds - well past Safari's transient activation window it seems.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Fix and the Takeaways
&lt;/h2&gt;

&lt;p&gt;Honestly, this was a fundamental user agent limitation, and there was no clever code trick to bypass it. While &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/UserActivation/isActive" rel="noopener noreferrer"&gt;&lt;code&gt;navigation.userActivation.isActive()&lt;/code&gt;&lt;/a&gt; can tell you if transient activation is present, you can't update it.&lt;/p&gt;

&lt;p&gt;Our most appropriate solution was to separate the "save" and "copy" actions. We implemented a separate "Copy Link" button that remained disabled while the save operation was in progress. Once the settings were saved, and the link was ready, the "Copy Link" button would become enabled again, allowing the user &lt;strong&gt;to explicitly click it to copy&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Nevertheless, this small bug provided some valuable lessons:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Cross-browser testing is non-negotiable. Never assume an API behaves identically across all browsers, even if you think you know it.&lt;/li&gt;
&lt;li&gt;Robust E2E tests need broad coverage. We had Playwright tests, but they were only running against Chromium. A major miss!&lt;/li&gt;
&lt;li&gt;Logging never hurts. Our detailed logs quickly pointed us to the correct error, even before I had to grab an iPhone.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Have you ever encountered a similar browser-specific gotcha? Share your war stories in the comments!&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>programming</category>
      <category>javascript</category>
      <category>safari</category>
    </item>
    <item>
      <title>🧠 JS Pop Quiz: ⚡️Faster iterations</title>
      <dc:creator>TusharShahi</dc:creator>
      <pubDate>Sat, 12 Apr 2025 18:53:50 +0000</pubDate>
      <link>https://forem.com/tusharshahi/js-pop-quiz-faster-iterations-3n39</link>
      <guid>https://forem.com/tusharshahi/js-pop-quiz-faster-iterations-3n39</guid>
      <description>&lt;p&gt;Can you make a one-liner change to the below to ~100x its performance?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  const ans = hugeArray
    .filter((item) =&amp;gt; item.isEven)
    .map((item) =&amp;gt; calculateSumOfDigits(item.id))
    .some((item) =&amp;gt; {
      return item &amp;gt; 20;
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you have the answer feel free to skip the rest of the article. If not, then the below write-up might help you.&lt;/p&gt;

&lt;h2&gt;
  
  
  Array methods: declarative and descriptive
&lt;/h2&gt;

&lt;p&gt;Array methods like &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" rel="noopener noreferrer"&gt;&lt;code&gt;Array.protoype.map()&lt;/code&gt;&lt;/a&gt;, &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" rel="noopener noreferrer"&gt;&lt;code&gt;Array.protoype.filter()&lt;/code&gt;&lt;/a&gt; were introduced more than 10 years back in JavaScript and have found great adoption. In this last decade, these friendly helpers have slowly and surely become integral to our JS codebases. Not just because they improve code readability, but also because they align with &lt;a href="https://h4iuiuc.notion.site/Functional-Javascript-b37bfb4171a54907ace2c8cf4a99f9a2" rel="noopener noreferrer"&gt;functional programming&lt;/a&gt; paradigm where the guideline is to be more declarative than iterative.&lt;/p&gt;

&lt;p&gt;The above code can be easily written with a for loop. Some folks might even point out that a for loop would be more performant. But given how well code these methods have integrated into our daily life as JS developers, it would not be surprising to find. Even if not in practicality, it is crucial to know how the above is non-performant when compared to its alternative.&lt;/p&gt;

&lt;h2&gt;
  
  
  What's the problem?
&lt;/h2&gt;

&lt;p&gt;Methods like &lt;code&gt;Array.protoype.map()&lt;/code&gt;, &lt;code&gt;Array.protoype.filter()&lt;/code&gt; etc. return new arrays without modifying the existing ones. That is one of the biggest advantages they come with. It seems clear that in the above code snippet, we are creating 2 intermediary arrays. Given we are working with a huge array (with 100000 elements), this might not be ideal. Why do something that's not needed? That is precisely why a simple for loop would be much more efficient above.&lt;/p&gt;

&lt;p&gt;But is there a way we can still have declarative behavior, while not losing out on performance?&lt;/p&gt;

&lt;h2&gt;
  
  
  Using iterables
&lt;/h2&gt;

&lt;p&gt;Converting the array to an iterator object and then iterating on it gives us a huge performance boost.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  const ans = hugeArray
    .values() 
    .filter((item) =&amp;gt; item.isEven)
    .map((item) =&amp;gt; calculateSumOfDigits(item.id))
    .some((item) =&amp;gt; {
      return item &amp;gt; 20;
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/values" rel="noopener noreferrer"&gt;&lt;code&gt;Array.prototype.values()&lt;/code&gt;&lt;/a&gt; returns an iterator object that iterates the values of each item in the array.&lt;/p&gt;

&lt;p&gt;So instead of calling array methods like &lt;code&gt;Array.protoype.map()&lt;/code&gt; and &lt;code&gt;Array.protoype.filter()&lt;/code&gt;, we will call &lt;code&gt;Iterator.protoype.map()&lt;/code&gt; and &lt;code&gt;Iterator.protoype.filter()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The biggest difference between &lt;code&gt;Array.protoype.filter()&lt;/code&gt; and &lt;code&gt;Iterator.protoype.filter()&lt;/code&gt; is that the latter does not create an array at all. &lt;/p&gt;

&lt;p&gt;The difference is staggering both in terms of performance and memory usage. Below is a dry run for a 100000 records.&lt;/p&gt;

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

&lt;p&gt;Without &lt;code&gt;.values()&lt;/code&gt; it takes 4ms, and with &lt;code&gt;.values()&lt;/code&gt; it takes just 0.06ms. The memory footprint is also lower since we are not creating new arrays. The gap widens even more when the array has even more elements.&lt;/p&gt;

&lt;p&gt;The above Iterator methods are new addition to Javascript and are supported in recent versions of both Node and Browsers. For example, I ran the above on Node 22. This addition might also promote the adoption of generators.&lt;/p&gt;

&lt;h2&gt;
  
  
  Generator Usage
&lt;/h2&gt;

&lt;p&gt;A Generator object (returned from generator functions) is just another type of iterator object. The key feature has always been the fact that the values yielded from a generator object are not evaluated until used. One of the major reasons for low adoption of generators was cited to be the lack of declarative helper methods like &lt;code&gt;map()&lt;/code&gt;, &lt;code&gt;filter()&lt;/code&gt; etc. Now, that these methods are available, it becomes easier to replace existing array implementations with generators. As seen above this reduces both an operations processing time and its memory footprint.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>javascript</category>
      <category>performance</category>
      <category>beginners</category>
    </item>
    <item>
      <title>[Boost]</title>
      <dc:creator>TusharShahi</dc:creator>
      <pubDate>Sat, 05 Apr 2025 06:18:46 +0000</pubDate>
      <link>https://forem.com/tusharshahi/-5aaf</link>
      <guid>https://forem.com/tusharshahi/-5aaf</guid>
      <description>&lt;div class="ltag__link--embedded"&gt;
  &lt;div class="crayons-story "&gt;
  &lt;a href="https://dev.to/tusharshahi/nextjs-vulnerability-which-is-forcing-everyone-to-upgrade-37a6" class="crayons-story__hidden-navigation-link"&gt;Understanding CVE-2025-29927 - The Next.js Vulnerability&lt;/a&gt;


  &lt;div class="crayons-story__body crayons-story__body-full_post"&gt;
    &lt;div class="crayons-story__top"&gt;
      &lt;div class="crayons-story__meta"&gt;
        &lt;div class="crayons-story__author-pic"&gt;

          &lt;a href="/tusharshahi" class="crayons-avatar  crayons-avatar--l  "&gt;
            &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F486783%2F6ada7af5-1aa7-4488-98c1-81b45d88dcd9.png" alt="tusharshahi profile" class="crayons-avatar__image"&gt;
          &lt;/a&gt;
        &lt;/div&gt;
        &lt;div&gt;
          &lt;div&gt;
            &lt;a href="/tusharshahi" class="crayons-story__secondary fw-medium m:hidden"&gt;
              TusharShahi
            &lt;/a&gt;
            &lt;div class="profile-preview-card relative mb-4 s:mb-0 fw-medium hidden m:inline-block"&gt;
              
                TusharShahi
                
              
              &lt;div id="story-author-preview-content-2381752" class="profile-preview-card__content crayons-dropdown branded-7 p-4 pt-0"&gt;
                &lt;div class="gap-4 grid"&gt;
                  &lt;div class="-mt-4"&gt;
                    &lt;a href="/tusharshahi" class="flex"&gt;
                      &lt;span class="crayons-avatar crayons-avatar--xl mr-2 shrink-0"&gt;
                        &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F486783%2F6ada7af5-1aa7-4488-98c1-81b45d88dcd9.png" class="crayons-avatar__image" alt=""&gt;
                      &lt;/span&gt;
                      &lt;span class="crayons-link crayons-subtitle-2 mt-5"&gt;TusharShahi&lt;/span&gt;
                    &lt;/a&gt;
                  &lt;/div&gt;
                  &lt;div class="print-hidden"&gt;
                    
                      Follow
                    
                  &lt;/div&gt;
                  &lt;div class="author-preview-metadata-container"&gt;&lt;/div&gt;
                &lt;/div&gt;
              &lt;/div&gt;
            &lt;/div&gt;

          &lt;/div&gt;
          &lt;a href="https://dev.to/tusharshahi/nextjs-vulnerability-which-is-forcing-everyone-to-upgrade-37a6" class="crayons-story__tertiary fs-xs"&gt;&lt;time&gt;Apr 4 '25&lt;/time&gt;&lt;span class="time-ago-indicator-initial-placeholder"&gt;&lt;/span&gt;&lt;/a&gt;
        &lt;/div&gt;
      &lt;/div&gt;

    &lt;/div&gt;

    &lt;div class="crayons-story__indention"&gt;
      &lt;h2 class="crayons-story__title crayons-story__title-full_post"&gt;
        &lt;a href="https://dev.to/tusharshahi/nextjs-vulnerability-which-is-forcing-everyone-to-upgrade-37a6" id="article-link-2381752"&gt;
          Understanding CVE-2025-29927 - The Next.js Vulnerability
        &lt;/a&gt;
      &lt;/h2&gt;
        &lt;div class="crayons-story__tags"&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/webdev"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;webdev&lt;/a&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/programming"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;programming&lt;/a&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/javascript"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;javascript&lt;/a&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/security"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;security&lt;/a&gt;
        &lt;/div&gt;
      &lt;div class="crayons-story__bottom"&gt;
        &lt;div class="crayons-story__details"&gt;
          &lt;a href="https://dev.to/tusharshahi/nextjs-vulnerability-which-is-forcing-everyone-to-upgrade-37a6" class="crayons-btn crayons-btn--s crayons-btn--ghost crayons-btn--icon-left"&gt;
            &lt;div class="multiple_reactions_aggregate"&gt;
              &lt;span class="multiple_reactions_icons_container"&gt;
                  &lt;span class="crayons_icon_container"&gt;
                    &lt;img src="https://assets.dev.to/assets/sparkle-heart-5f9bee3767e18deb1bb725290cb151c25234768a0e9a2bd39370c382d02920cf.svg" width="18" height="18"&gt;
                  &lt;/span&gt;
              &lt;/span&gt;
              &lt;span class="aggregate_reactions_counter"&gt;1&lt;span class="hidden s:inline"&gt; reaction&lt;/span&gt;&lt;/span&gt;
            &lt;/div&gt;
          &lt;/a&gt;
            &lt;a href="https://dev.to/tusharshahi/nextjs-vulnerability-which-is-forcing-everyone-to-upgrade-37a6#comments" class="crayons-btn crayons-btn--s crayons-btn--ghost crayons-btn--icon-left flex items-center"&gt;
              Comments


              &lt;span class="hidden s:inline"&gt;Add Comment&lt;/span&gt;
            &lt;/a&gt;
        &lt;/div&gt;
        &lt;div class="crayons-story__save"&gt;
          &lt;small class="crayons-story__tertiary fs-xs mr-2"&gt;
            3 min read
          &lt;/small&gt;
            
              &lt;span class="bm-initial"&gt;
                

              &lt;/span&gt;
              &lt;span class="bm-success"&gt;
                

              &lt;/span&gt;
            
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;/div&gt;


</description>
      <category>webdev</category>
      <category>programming</category>
      <category>javascript</category>
      <category>security</category>
    </item>
    <item>
      <title>Understanding CVE-2025-29927 - The Next.js Vulnerability</title>
      <dc:creator>TusharShahi</dc:creator>
      <pubDate>Fri, 04 Apr 2025 19:01:29 +0000</pubDate>
      <link>https://forem.com/tusharshahi/nextjs-vulnerability-which-is-forcing-everyone-to-upgrade-37a6</link>
      <guid>https://forem.com/tusharshahi/nextjs-vulnerability-which-is-forcing-everyone-to-upgrade-37a6</guid>
      <description>&lt;p&gt;I love working with Next.js and have used it in projects since version 10 came out. The release of middleware in version 12 was exciting as it moved the framework closer to a full-stack framework.&lt;/p&gt;

&lt;p&gt;Recently, a vulnerability in the middleware layer took the world by storm. The issue existed for around 3 years, back until version 12 of Next.js. With this post, I aim to summarize the vulnerability.&lt;/p&gt;

&lt;h2&gt;
  
  
  The vulnerability - CVE-2025-29927
&lt;/h2&gt;

&lt;p&gt;Internally, Next.js uses a function that determines whether the middleware function should be run. The code was such that if a specific header is passed in with the request, the middleware would be skipped and the request would directly hit the server.&lt;/p&gt;

&lt;p&gt;The header's name was &lt;code&gt;x-middleware-subrequest&lt;/code&gt;. The idea was to it as an internal header that would help identify if a middleware has been run before, and based on that prevent the triggering of infinite loops due to recursive requests. &lt;/p&gt;

&lt;p&gt;This intentional implementation is a vulnerability specifically for apps where authentication logic relies solely on this middleware layer. Since, once a request gets past the middleware there is no further check.&lt;/p&gt;

&lt;h2&gt;
  
  
  Code breakdown
&lt;/h2&gt;

&lt;p&gt;In the newer version of Next.js (before the vulnerability was fixed) the code looks like this:&lt;/p&gt;

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

&lt;p&gt;While the complete implementation is not something I dived into: It seems like we are trying to limit the recursive depth of Next.js middleware invocation to 5. Once that happens, we will return with the response without running the rest of the logic.&lt;/p&gt;

&lt;p&gt;It is even more apparent in one of the earlier versions. This is a &lt;a href="https://github.com/vercel/next.js/commit/1c199a5e4a158685007c006820e6eaec94796528#diff-9068f41c0d182a2aeb07d48d7a777a89481dc75d332453fca00970c5b6f2b0aa" rel="noopener noreferrer"&gt;code snippet&lt;/a&gt; from Dec 2021.&lt;/p&gt;

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

&lt;p&gt;Here it seems we are simply skipping the middleware logic if the array of subrequests includes the middleware name. We execute the run function with the following parameters where the argument &lt;code&gt;name&lt;/code&gt; corresponds to the middleware name.&lt;/p&gt;

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

&lt;h2&gt;
  
  
  The header
&lt;/h2&gt;

&lt;p&gt;So, it seems given the right value of this header we can prevent the logic of middleware from running. In Next.js, middlewares are supposed to be named &lt;code&gt;middleware.ts&lt;/code&gt; or &lt;code&gt;middleware.js&lt;/code&gt;. Depending on the version of Next.js, they might be placed in different sub-folders but even then a middleware's path can be guessed. That is why this vulnerability is easier to take advantage of.&lt;/p&gt;

&lt;p&gt;The header &lt;code&gt;x-middleware-subrequest&lt;/code&gt; is supposed to be an internal header that is supposed to be set from the middleware and its value be modified at the middleware level itself. But by sending specific values in this header a middleware can be bypassed.&lt;/p&gt;

&lt;p&gt;The exact value of this header is different for different versions of Next.js. For example:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;For versions before 12.2:&lt;/strong&gt; &lt;code&gt;pages/_middleware&lt;/code&gt; or &lt;code&gt;pages/dashboard/_middleware&lt;/code&gt; based on the route on which the middleware is placed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;For versions starting 12.2:&lt;/strong&gt; &lt;code&gt;middleware&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;For version starting 14:&lt;/strong&gt; &lt;code&gt;middleware:middleware:middleware:middleware:middleware&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;There are other nuances such as the existence of a &lt;code&gt;src&lt;/code&gt; folder, but the overall gist is that the value can be guessed in a few attempts.&lt;/p&gt;

&lt;h2&gt;
  
  
  Learnings
&lt;/h2&gt;

&lt;p&gt;There is a lot to learn from this whole incident. Below are some of the key learnings I will take with me:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Do not use Next.js middlewares as the sole method for protecting the App.&lt;/strong&gt; Even &lt;a href="https://vercel.com/blog/postmortem-on-next-js-middleware-bypass#technical-analysis" rel="noopener noreferrer"&gt;Next.js recommends&lt;/a&gt; against it. They do suggest using the middleware for optimistic redirecting, for example: missing cookie.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Every security issue should be treated as P0.&lt;/strong&gt; Next.js team was &lt;a href="https://vercel.com/blog/postmortem-on-next-js-middleware-bypass#2025-02-27" rel="noopener noreferrer"&gt;notified of this issue in Feb&lt;/a&gt;, but at the time it seemed to only exist in older versions and that is why it was not acted upon immediately. Later it turned out to be an issue in even the newer versions of Next.js which have middleware.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Auth is hard.&lt;/strong&gt; For production-grade apps, it does not make sense to reinvent the wheel.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Never trust the client.&lt;/strong&gt; Technically anyone can manipulate request headers, and they should not be critical to such important logic.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Bonus
&lt;/h2&gt;

&lt;p&gt;For folks interested in watching a demo of the video. Please watch it here: &lt;a href="https://youtu.be/5j8aJiKrbgU" rel="noopener noreferrer"&gt;https://youtu.be/5j8aJiKrbgU&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;Note: For folks interested in understanding the complete issue, please visit &lt;a href="https://zhero-web-sec.github.io/research-and-things/nextjs-and-the-corrupt-middleware" rel="noopener noreferrer"&gt;this blog&lt;/a&gt; from Rachid A. which serves as an inspiration for this one too.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>programming</category>
      <category>javascript</category>
      <category>security</category>
    </item>
    <item>
      <title>The convenience of CSS's new @position-try</title>
      <dc:creator>TusharShahi</dc:creator>
      <pubDate>Wed, 16 Oct 2024 13:32:30 +0000</pubDate>
      <link>https://forem.com/tusharshahi/the-convenience-of-csss-new-position-try-28gn</link>
      <guid>https://forem.com/tusharshahi/the-convenience-of-csss-new-position-try-28gn</guid>
      <description>&lt;p&gt;CSS anchor positioning came out some time ago. If you, like me, do not like writing CSS, this new API would definitely improve things.&lt;/p&gt;

&lt;h2&gt;
  
  
  Anchor Positioning
&lt;/h2&gt;

&lt;p&gt;The CSS Anchor Positioning API allows developers to easily position elements relative to others (known as anchors), without needing extra libraries or complex JavaScript. This feature is perfect for creating menus, tooltips, dialogs, and other layered interfaces.&lt;/p&gt;

&lt;p&gt;With this API, you can ensure that an element's size/position adapts based on its anchor. This eliminates the need for manual adjustments and provides a smoother, more responsive experience when building dynamic, interactive layouts.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is position-try?
&lt;/h2&gt;

&lt;p&gt;Anchor CSS also came out with a new CSS at-rule called &lt;strong&gt;position-try&lt;/strong&gt;.  It allows you to define fallback positions for anchored elements when they don’t fit within the screen or container. If an element overflows, the browser automatically chooses the next alternative position, ensuring it stays fully visible and functional. The &lt;strong&gt;position-try-fallbacks&lt;/strong&gt; property can be used to define multiple fallback positions for the browser to &lt;strong&gt;try&lt;/strong&gt;. Earlier this would have been achieved by running a listener that checks after every viewport change if things are going. &lt;/p&gt;

&lt;p&gt;This could prevent a lot of headaches while working with dropdowns, tooltips etc. as now we do not have to write custom logic to check for overflow conditions.&lt;/p&gt;

&lt;h2&gt;
  
  
  A demo
&lt;/h2&gt;

&lt;p&gt;Here is a quick demo of the code I wrote using the above CSS properties:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqm9q8dmzkl3lfmw9q97l.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqm9q8dmzkl3lfmw9q97l.gif" alt="Demo of submenu changing its position based on viewport boundaries" width="600" height="338"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The submenu in my horrible-looking nav bar changes its position based on the width of the view port.&lt;/p&gt;

&lt;p&gt;The code is written in React. Earlier I would have had to use an effect to do this. In my effect, I would have checked if the submenu element is crossing the viewport's boundary. If yes, I would have triggered another re-render to update the styles of the submenu. Since useEffect runs after the paint, and we don't want the user to see the submenu in the wrong location, I would have had to use useLayoutEffect for this.&lt;/p&gt;

&lt;p&gt;Now all I have to do is write a CSS like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.button-anchor {
  anchor-name: --anchorButton;
}

@position-try --bottom {
  position-area: bottom;
}

.menu-list {
  position-anchor: --anchorButton;
  border: 1px solid #000;
  font-family: sans-serif;
  width: 60px;
  font-size: 12px;
  display: flex;
  flex-direction: column;
  row-gap: 4px;
  padding: 8px;
  position: fixed;
  position-area: right span-y-end;
  position-try-fallbacks: --bottom;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;@position-try&lt;/code&gt; - creates the rule called &lt;code&gt;--bottom&lt;/code&gt;.&lt;br&gt;
&lt;code&gt;anchor-name&lt;/code&gt; - sets the button as an anchor element.&lt;br&gt;
&lt;code&gt;position-anchor&lt;/code&gt; - lets menu-list use --anchorButton as the anchor element.&lt;br&gt;
&lt;code&gt;position-try-fallbacks&lt;/code&gt; - helps list the multiple fallbacks to try. This means there can be more positions even if &lt;code&gt;--bottom&lt;/code&gt; fails.&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;Anchor CSS has come and solved some very interesting use cases for a developer. In addition to the above, tethered positioning becomes very easy. Everything is purely on CSS, so performance is also great.  Right now the browser support is not great, but I hope it sees more adoption soon.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>css</category>
      <category>react</category>
      <category>todayilearned</category>
    </item>
    <item>
      <title>UI Blocking behaviour: microtasks vs macrotasks</title>
      <dc:creator>TusharShahi</dc:creator>
      <pubDate>Fri, 30 Aug 2024 14:48:53 +0000</pubDate>
      <link>https://forem.com/tusharshahi/ui-blocking-behaviour-microtasks-vs-macrotasks-4en1</link>
      <guid>https://forem.com/tusharshahi/ui-blocking-behaviour-microtasks-vs-macrotasks-4en1</guid>
      <description>&lt;p&gt;Can you find the difference between the two code snippets below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function handleClick1() {
     setTimeout(handleClick1, 0);
}

function handleClick2() {
     Promise.resolve().then(handleClick2);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you are not able to identify the implications of choosing one over the other, then this blog post will teach you something new.&lt;/p&gt;

&lt;h2&gt;
  
  
  Background
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;setTimeout&lt;/code&gt; is for scheduling a callback after a certain amount of time. &lt;code&gt;Promise.resolve().then&lt;/code&gt; will do the same thing effectively, but internally both are different. The latter returns a promise, that is already resolved. Calling &lt;code&gt;then(callback)&lt;/code&gt; on that promise will schedule &lt;code&gt;callback&lt;/code&gt; to be executed.&lt;/p&gt;

&lt;p&gt;So both the above functions call themselves recursively with minimal delay. The difference is that callback from &lt;code&gt;setTimeout&lt;/code&gt; is placed in macrotask queue and a callback from a &lt;code&gt;promise.then()&lt;/code&gt; is placed in microtask queue. How the event loop treats items from these two queues is what makes the above 2 code snippets the difference.&lt;/p&gt;

&lt;h2&gt;
  
  
  Event loop treatment of microtask vs macrotask
&lt;/h2&gt;

&lt;p&gt;All an event loop does is while there are tasks to perform, it performs them and then sleeps and waits for other tasks. &lt;/p&gt;

&lt;p&gt;Macrotasks (or simply tasks) include functions responsible for work such as:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Parsing&lt;/li&gt;
&lt;li&gt;Reacting to DOM,&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;among others...&lt;/p&gt;

&lt;p&gt;After the execution of a task picked from the task queue, the event loop performs a &lt;a href="https://html.spec.whatwg.org/multipage/webappapis.html#perform-a-microtask-checkpoint" rel="noopener noreferrer"&gt;&lt;code&gt;microtask checkpoint&lt;/code&gt;&lt;/a&gt;. The algo for which is something like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;While microtask queue is not empty, pick the oldest task from microtask queue and execute it.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What this means is that if a microtask enqueues another microtask that task will be executed before the next macrotask. And since UI rendering is a macrotask, it will never be executed by the event loop.&lt;/p&gt;

&lt;p&gt;Here is a demo for the above: &lt;a href="https://jsbin.com/mezemasili/1/edit?html,css,js,console,output" rel="noopener noreferrer"&gt;JS Bin demo&lt;/a&gt;. An infinite animation is running. If we trigger &lt;code&gt;handleClick1&lt;/code&gt; then we add some processing to the main thread, but the animation still renders correctly. But if we trigger &lt;code&gt;handleClick2&lt;/code&gt; the animation stops.&lt;/p&gt;

&lt;p&gt;I have added the variable &lt;code&gt;totalCount&lt;/code&gt;, so we can break before the page crashes. But what is noticeable is that once the microTask loop is started, the UI becomes unresponsive for some time.. Because tasks like rendering, reacting to DOM etc. will only be executed after the microtask queue is empty.&lt;/p&gt;

&lt;p&gt;This makes &lt;code&gt;handleClick1&lt;/code&gt; from the above code snippet a safer choice. Hope the blog helped explain one fundamental difference between microtasks and macrotasks.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>webperf</category>
      <category>programming</category>
    </item>
    <item>
      <title>TypeScript Tip #3: Folder-wise config</title>
      <dc:creator>TusharShahi</dc:creator>
      <pubDate>Thu, 25 Apr 2024 06:05:59 +0000</pubDate>
      <link>https://forem.com/tusharshahi/typescript-tip-3-folder-wise-config-2501</link>
      <guid>https://forem.com/tusharshahi/typescript-tip-3-folder-wise-config-2501</guid>
      <description>&lt;p&gt;The file &lt;code&gt;tsconfig.json&lt;/code&gt; indicates that the project is using typescript. It specifies the different options required to compile the project.&lt;/p&gt;

&lt;p&gt;There are situations when you are working on a huge project and migrating it from JavaScript to TypeScript. While new code is well-typed the older code is in a state where type-checking can not be as strict.&lt;/p&gt;

&lt;p&gt;The need arises for different levels of type strictness in different sub-folders of the same project. This can be achieved using multiple config files.&lt;/p&gt;

&lt;p&gt;Example: You do not allow the type &lt;code&gt;any&lt;/code&gt; in your new subfolder. But the rest of your project being much legacy, still uses &lt;code&gt;any&lt;/code&gt; here and there.&lt;/p&gt;

&lt;p&gt;You can have &lt;code&gt;"noImplicitAny": false&lt;/code&gt; in your main config file.&lt;/p&gt;

&lt;p&gt;Inside the new subfolder, you can have another &lt;code&gt;tsconfig.json&lt;/code&gt; file, which extends the main tsconfig.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "extends": "../../../tsconfig.json",
  "compilerOptions": {
    "noImplicitAny": true
  },
  "include": ["*"]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a game changer for huge projects and allows for agile development.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>typescript</category>
      <category>programming</category>
      <category>beginners</category>
    </item>
    <item>
      <title>TypeScript Tip #2: valueof</title>
      <dc:creator>TusharShahi</dc:creator>
      <pubDate>Tue, 16 Apr 2024 13:35:13 +0000</pubDate>
      <link>https://forem.com/tusharshahi/typescript-tip-2-valueof-a3e</link>
      <guid>https://forem.com/tusharshahi/typescript-tip-2-valueof-a3e</guid>
      <description>&lt;p&gt;While working on a TypeScript project, it is a common ask to restrict a type of variable to the value of the keys of an object.&lt;/p&gt;

&lt;p&gt;Suppose we have an object like the below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const statusMap = {
    pending : 'PENDING',
    finished : 'FINISHED',
    notStarted : 'NOT_STARTED'
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When we want to have a related &lt;code&gt;status&lt;/code&gt; variable, it can only have three values - PENDING, FINISHED and NOT_STARTED.&lt;/p&gt;

&lt;p&gt;The way to go about it is usually by narrowing the type of our object first:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const statusMap = {
    pending : 'PENDING',
    finished : 'FINISHED',
    notStarted : 'NOT_STARTED'
} as const;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using &lt;code&gt;as const&lt;/code&gt; or &lt;strong&gt;const assertion&lt;/strong&gt;, &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;we make &lt;code&gt;statusMap&lt;/code&gt; read-only, eg: &lt;code&gt;statusMap.pending&lt;/code&gt; cannot be modified.&lt;/li&gt;
&lt;li&gt;no literal types are widened. eg: type &lt;code&gt;PENDING&lt;/code&gt; does not become &lt;code&gt;string&lt;/code&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So given the above we usually end up creating a type like:&lt;/p&gt;

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

&lt;p&gt;We use &lt;code&gt;keyof&lt;/code&gt; and &lt;code&gt;typeof&lt;/code&gt; provided by Typescript and Javascript respectively to help us make the suitable type.&lt;/p&gt;

&lt;p&gt;This works well. But I would like to avoid writing the variable &lt;code&gt;statusMap&lt;/code&gt; twice. Imagine us having multiple variables like that and our code starts looking like this:&lt;/p&gt;

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

&lt;p&gt;It would be great if we could simplify it and reduce the duplication.&lt;br&gt;
To do that it is easy to create a type like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type valueof&amp;lt;X&amp;gt; = X[keyof X];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have created a generic called &lt;code&gt;valueof&lt;/code&gt;. We extract the values of the keys of type X and use them to make a template literal type.&lt;/p&gt;

&lt;p&gt;Now it works like the below and still works.&lt;/p&gt;

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

&lt;p&gt;&lt;code&gt;valueOf&lt;/code&gt; seems so convenient that I am surprised it is not available in TypeScript out-of-the-box. I hope you guys also find use of it.&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>webdev</category>
      <category>programming</category>
      <category>beginners</category>
    </item>
    <item>
      <title>TypeScript Tip #1: forEach vs for loop</title>
      <dc:creator>TusharShahi</dc:creator>
      <pubDate>Sun, 14 Apr 2024 02:41:01 +0000</pubDate>
      <link>https://forem.com/tusharshahi/typescript-tip-1-foreach-vs-for-loop-56og</link>
      <guid>https://forem.com/tusharshahi/typescript-tip-1-foreach-vs-for-loop-56og</guid>
      <description>&lt;p&gt;While working on a typescript project, it is recommended to enable &lt;a href="https://www.typescriptlang.org/tsconfig/noUncheckedIndexedAccess.html" rel="noopener noreferrer"&gt;&lt;code&gt;noUncheckedIndexedAccess&lt;/code&gt;&lt;/a&gt; for safer object access.&lt;/p&gt;

&lt;p&gt;The difference it makes can be summarised below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const obj : Record&amp;lt;string,number[]&amp;gt; = {};

obj.nonExistentKey.push(2);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Without enabling the flag the above will not throw an error. Above is a trivial example but I hope it shows the importance of this flag.&lt;/p&gt;

&lt;p&gt;Enabling this flag leads to another hurdle though:&lt;/p&gt;

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

&lt;p&gt;The error says: &lt;strong&gt;Type 'undefined' is not assignable to type 'number'&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;arr[i]&lt;/code&gt; is inferred as &lt;code&gt;undefined&lt;/code&gt; inside the for loop. Why though?&lt;/p&gt;

&lt;p&gt;Because the length of the above array can be changed like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;arr[15]=2;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, &lt;code&gt;arr.length&lt;/code&gt; is 16. The array is &lt;a href="https://www.freecodecamp.org/news/sparse-and-dense-arrays-in-javascript/#:~:text=A%20sparse%20array%20is%20one,the%20sequence%20of%20their%20indices.&amp;amp;text=Normally%2C%20the%20length%20property%20of,sparse%20arrays%20they%20don't." rel="noopener noreferrer"&gt;sparse&lt;/a&gt; and has "holes" or "empty slots" in it. Accessing these elements will give &lt;code&gt;undefined&lt;/code&gt;. Hence TypeScript complains.&lt;/p&gt;

&lt;p&gt;So how to fix it?&lt;/p&gt;

&lt;p&gt;We can use an array method like &lt;code&gt;forEach&lt;/code&gt;. Looking at the &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#description" rel="noopener noreferrer"&gt;documentation&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.&lt;/p&gt;
&lt;/blockquote&gt;

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

&lt;p&gt;Here is the typescript &lt;a href="https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true#code/MYewdgzgLgBAhgJwTAXDMBXAtgIwKYIDaAujALwyECMANAEw0DMxA3ALABQnoksANiADmAOWz5kFABQA3OH1ToxBAJTkAfDADenGLpg8IIPngB0AwTLnL2HAL6dOAMxAJJx2AEtyMAAwwWMF4APPBIZnhgglAAFiweANTxytocejDmorgEkohEHsTWnPZcJbkmzggAonDA0ZKSAB6qZBoZSq5N1kA" rel="noopener noreferrer"&gt;playground&lt;/a&gt; for you to play around with.&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>webdev</category>
      <category>programming</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Cost of unnecessary Optional Chaining (and Nullish coalescing operator)</title>
      <dc:creator>TusharShahi</dc:creator>
      <pubDate>Sat, 06 Apr 2024 14:51:14 +0000</pubDate>
      <link>https://forem.com/tusharshahi/cost-of-unnecessary-optional-chaining-and-nullish-coalescing-operator-3h09</link>
      <guid>https://forem.com/tusharshahi/cost-of-unnecessary-optional-chaining-and-nullish-coalescing-operator-3h09</guid>
      <description>&lt;p&gt;If you are a developer who has worked with JavaScript in recent years, I am sure you are well aware of the below syntax:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const a = obj1?.x; 
const b = obj2.c ?? '2'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We see them all around us, making our lives easier.&lt;/p&gt;

&lt;p&gt;The first one is &lt;a href="https://javascript.info/optional-chaining" rel="noopener noreferrer"&gt;optional chaining&lt;/a&gt; and the other one is the &lt;a href="https://javascript.info/nullish-coalescing-operator" rel="noopener noreferrer"&gt;nullish coalescing operator&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Both of them are so easy to use that they have a huge adoption in a lot of code bases. They help protect us from the embarrassing situation of our webapp breaking in production. But there is a cost to their overuse which will make one debate their pros and cons.&lt;/p&gt;

&lt;h2&gt;
  
  
  Background
&lt;/h2&gt;

&lt;p&gt;As we can see from the docs, both are recent additions to the language. This means to get them to work on older browsers, they need polyfills.&lt;/p&gt;

&lt;p&gt;We can open our dev tools and write something like &lt;code&gt;window?.testing&lt;/code&gt; and it will not complain. But if we do the same on an older browser, it will throw us an error.&lt;/p&gt;

&lt;p&gt;For our nice new syntax to work on old outdated browsers, it is converted into (probably) longer and more primitive code. This whole logic is what a polyfill is. It is a script that updates/adds new functions. &lt;/p&gt;

&lt;h2&gt;
  
  
  Babel
&lt;/h2&gt;

&lt;p&gt;So, how is this working out in the case of our React apps. We never have to worry about writing some polyfill. The reason for that is &lt;code&gt;Babel&lt;/code&gt;. Babel, a transpiler, converts modern JavaScipt code to make it easily understandable to most browsers. We get to decide the target browsers we plan on supporting and Babel does the conversion.&lt;/p&gt;

&lt;p&gt;Your code might not use Babel but some other transpiler like SWC, but the funda is common. Convert new-fashioned code into code that most browsers can understand.&lt;/p&gt;

&lt;p&gt;All this is part of the bundling process, with the final aim of converting our React code into a group of JS, CSS and HTML files.&lt;/p&gt;

&lt;h2&gt;
  
  
  Being extra cautious
&lt;/h2&gt;

&lt;p&gt;Coming to the topic that encouraged me to write this blog. I was reviewing a code and saw something like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      if (cityName) {
        if (location === cityName)
          res.writeHead(301, {
            Location: `/somegibberish/${cityName?.toLowerCase()}/`,
          });
        else
          res.writeHead(301, {
            Location: `/somegibberish/${cityName?.toLowerCase()}/${localitySlug}`,
          });
      }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;I pointed out the problem:&lt;/strong&gt; &lt;code&gt;cityName&lt;/code&gt; is checked once at the top level, and inside the &lt;code&gt;if&lt;/code&gt; branch, optional chaining is used to check the (somewhat) same thing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The response:&lt;/strong&gt; Although unnecessary, there is no harm in doing that.&lt;/p&gt;

&lt;p&gt;The first harm I could see was in setting the wrong expectations. If the above code block became much larger with multiple contexts like function calls, it would be hard to track whether &lt;code&gt;cityName&lt;/code&gt; can be &lt;code&gt;falsy&lt;/code&gt;. (This is a problem, more specific to JS-only code bases)&lt;/p&gt;

&lt;p&gt;The second is something I found out only when looking at the bundle output.&lt;/p&gt;

&lt;h2&gt;
  
  
  Transpiling
&lt;/h2&gt;

&lt;p&gt;The code written above will not go as it is into our bundle. As already established, it will get converted into old-school JS so we can target as many browsers (in turn as many users) as possible.&lt;/p&gt;

&lt;p&gt;Here is the screenshot of what optional chaining and nullish coalescing operator code gets converted into.&lt;/p&gt;

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

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

&lt;p&gt;Let us pick any one of them. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Nullish Coalescing Operator:&lt;/strong&gt; a logical operator that returns its right-hand side operand when its left-hand side operand is &lt;code&gt;null&lt;/code&gt; or &lt;code&gt;undefined&lt;/code&gt;, and otherwise returns its left-hand side operand.&lt;/p&gt;

&lt;p&gt;Something like &lt;code&gt;x ?? '2'&lt;/code&gt; gets converted into &lt;code&gt;x !== null &amp;amp;&amp;amp; x !== void 0 ? x : '2'&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;void 0&lt;/code&gt; is not something you see every day. It is the old way of writing &lt;code&gt;undefined&lt;/code&gt;. It is favored over directly writing &lt;code&gt;undefined&lt;/code&gt; for 2 reasons:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;In older JS specifications, &lt;code&gt;undefined&lt;/code&gt; was not a reserved word. One could literally do &lt;code&gt;var undefined = 'defined'&lt;/code&gt;. (This is no longer a problem)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;undefined&lt;/code&gt; takes more bits than &lt;code&gt;void 0&lt;/code&gt;. Which definitely is a good enough reason to use it, when our bundle will be filled with it.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Cost to the bundle
&lt;/h2&gt;

&lt;p&gt;Here is how the above code snippet, sat in our code bundle:&lt;/p&gt;

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

&lt;p&gt;The above gives a sense of the problem with using optional chaining and NCO (in short :P) blindly, even more so in situations where they are not required. The bundle size can increase massively, even after modification. &lt;/p&gt;

&lt;p&gt;I would still use the above two features, but I strongly advise not to use them unnecessarily now that I have seen the bundle output.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bonus:&lt;/strong&gt; Here is an es-lint rule that might help: &lt;a href="https://typescript-eslint.io/rules/no-unnecessary-condition/" rel="noopener noreferrer"&gt;&lt;code&gt;no-unnecessary-condition&lt;/code&gt;&lt;/a&gt; in pruning out all those unnecessary checks. &lt;/p&gt;

</description>
      <category>performance</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
